網站首頁 編程語言 正文
使用jpype調用Jar包中的實現方法
安裝
pip install jpype1(注意要加后邊這個1)
使用
基本流程如下:
- 使用jpype開啟jvm
- 加載java類
- 調用java方法
- 關閉jvm
說明
我這里是在Python中使用Java的第三方抽象語法樹包JavaParser(Python中的javalang實在太難用了),實現得到一個類文件中的所有的方法的功能
代碼
Python代碼:
import jpype import os import json if __name__ == '__main__': ? ? # 加載jar包 ? ? jarpath = os.path.join(os.path.abspath('.'),'D:/study/hdu-cs-learning/Paper/TD/BuildDataset/target/BuildDataset.jar') ? ? # 獲取jvm.dll的默認文件路徑 ? ? jvmPath = jpype.getDefaultJVMPath() ? ? # 開啟虛擬機 ? ? jpype.startJVM(jvmPath, '-ea', '-Djava.class.path=%s' % (jarpath)) ? ? # 加載java類(參數名是java的長類名) ? ? javaClass = jpype.JClass('scluis.API') ? ? # 調用類中的方法 ? ? class_file_path = 'D:/study/TD/OpenSourceProject/JFreeChart/source/org/jfree/chart/fx/ChartViewer.java' ? ? # 這里是調用scluis.API類的靜態方法getMethods,如果調用實例方法,則需要先實例化java對象,即javaInstance = javaClass(),在使用實例調用 ? ? file_methods_str = javaClass.getMethods(class_file_path) ? ? # 解析返回值,這里的返回值是json數組 ? ? methods_list = "" ? ? if file_methods_str != "": ? ? ? ? methods_list = json.loads(str(file_methods_str)) ? ? # 關閉虛擬機 ? ? jpype.shutdownJVM()
API.java:
package scluis; import com.github.javaparser.ParseException; import java.io.IOException; import java.security.SecureRandom; import java.util.Random; public class API { ? ? public static void main(String[] args) { ? ? ?? ?//main方法是為了測試Java代碼即,getMethods,main方法不是必須的 ? ? ? ? String filePath="D:/study/OpenSourceProject/SQuirrel/app/src/net/sourceforge/squirrel_sql/client/gui/HelpViewerWindow.java"; ? ? ? ? String methods=getMethods(filePath); ? ? ? ? System.out.println(methods); ? ? } ? ? public static String getMethods(String filePath){ ? ? ? ? String res=""; ? ? ? ? try { ? ? ? ? ? ? Parser fileParser = new Parser(); ? ? ? ? ? ? res= fileParser.getFileMethods(filePath); ? ? ? ? } catch (ParseException | IOException e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? ? ? return res; ? ? } }
Parser.java(內含Java返回值格式)
package scluis; import com.alibaba.fastjson.JSON; import com.github.javaparser.*; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.comments.Comment; import com.github.javaparser.ast.expr.*; import com.github.javaparser.ast.stmt.BlockStmt; import com.github.javaparser.ast.stmt.ExpressionStmt; import com.github.javaparser.ast.stmt.Statement; import com.github.javaparser.printer.DotPrinter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; public class Parser { ? ? private CompilationUnit m_CompilationUnit; ? ? public CompilationUnit getParsedFile() { ? ? ? ? return m_CompilationUnit; ? ? } ? ? public String getFileMethods(String filePath) throws ParseException, IOException { ? ? ? ? String methodJson = ""; ? ? ? ? try { ? ? ? ? ? ? m_CompilationUnit = StaticJavaParser.parse(new File(filePath)); ? ? ? ? ? ? FunctionVisitor functionVisitor = new FunctionVisitor(); ? ? ? ? ? ? functionVisitor.visit(m_CompilationUnit, null); ? ? ? ? ? ? ArrayList<MethodDeclaration> nodes = functionVisitor.getMethodDeclarations(); ? ? ? ? ? ? ArrayList<Method> methodList = new ArrayList<>(); ? ? ? ? ? ? for (int i = 0; i < nodes.size(); i++) { ? ? ? ? ? ? ? ? MethodDeclaration methodDeclaration = nodes.get(i); ? ? ? ? ? ? ? ? //起止行 ? ? ? ? ? ? ? ? int startLine = methodDeclaration.getRange().get().begin.line; ? ? ? ? ? ? ? ? int endLine = methodDeclaration.getRange().get().end.line; ? ? ? ? ? ? ? ? //方法代碼 ? ? ? ? ? ? ? ? String method = methodDeclaration.removeComment().toString(); ? ? ? ? ? ? ? ? Method m = new Method(startLine, endLine, method); ? ? ? ? ? ? ? ? methodList.add(m); ? ? ? ? ? ? } ? ? ? ? ? ? methodJson = JSON.toJSONString(methodList); ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? ? ? return methodJson; ? ? } }
jpype調用jar包“Class xx not found“問題
環境
- Java 1.8 (64位)
- Python 2.7.9 (32位)
- Jpype 0.5.4.2
- Pycharm
代碼
import jpype from jpype import * # 該目錄下有需要調用的jar包 pak.jar jvmArg = "-Djava.ext.dirs=D:/1_Workspace/jpype_test/" if not jpype.isJVMStarted(): jvmPath = jpype.getDefaultJVMPath() jpype.startJVM(jvmPath,"-ea", jvmArg) # pak.jar中包含類com.abc.EFG jd = JClass("com.abc.EFG") instance = jd() print(instance.getName()) jpype.shutdownJVM()
問題
執行以上代碼,報錯如下。Class com.abc.EFG not found
檢查點
1.在pak.jar包中有com.abc.EFG
類
2.EFG
依賴的jar包都在同級目錄下
3.Jpype使用沒有問題:調用System.out.println
可以打印
jprint = java.lang.System.out.println jprint("xxx") #輸出xxx
試著從環境上找原因,也許和Java版本有關。
首先查找pak.jar包的編譯jdk版本
使用以上方法獲得輸出是 52,即對應java 1.8,與本機Java版本相符。
但是回頭一想其實在Pycharm中并沒有配置過Java的版本。
那么打印一下jvmPath
,獲得的路徑是C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll
,=> 使用的是 jre1.6(32位)。
此時去Java1.8目錄找,發現server
目錄下有jvm.dll
,不是在client
目錄。管他的,嘗試直接指定存在的jvm.dll路徑。
# ... # jvmPath = jpype.getDefaultJVMPath() jvmPath = r'D:\java\jdk1.8\jre\bin\server\jvm.dll' jpype.startJVM(jvmPath,"-ea", jvmArg) # ...
到這里也許有人的問題可以解決了,但我的情況是還是報錯…
解決
最后裝了jdk1.8 32位!!!,發現在client
目錄下有jvm.dll
文件了
再次修改代碼,執行通過。
總結
原文鏈接:https://blog.csdn.net/weixin_42619772/article/details/122475997
相關推薦
- 2023-07-13 遍歷對象并改變對象某個屬性的值
- 2022-03-28 Easyx實現窗口自動碰撞的小球_C 語言
- 2022-05-12 小程序自定義日期組件,不顯示今日之后的日期
- 2023-07-18 SpringBoot中線程池初始化,并且可配置線程池參數
- 2022-11-27 VsCode運行html界面的實戰步驟_其它綜合
- 2022-04-01 FastDFS服務不能上傳文件 報錯:fileutil.MyException: getStoreS
- 2023-01-02 C++?命名空間?using聲明使用示例詳解_C 語言
- 2022-12-22 數據清洗之如何用一行Python代碼去掉文本中的各種符號_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支