網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
使用jpype調(diào)用Jar包中的實(shí)現(xiàn)方法
安裝
pip install jpype1(注意要加后邊這個(gè)1)
使用
基本流程如下:
- 使用jpype開(kāi)啟jvm
- 加載java類
- 調(diào)用java方法
- 關(guān)閉jvm
說(shuō)明
我這里是在Python中使用Java的第三方抽象語(yǔ)法樹(shù)包JavaParser(Python中的javalang實(shí)在太難用了),實(shí)現(xiàn)得到一個(gè)類文件中的所有的方法的功能
代碼
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的默認(rèn)文件路徑 ? ? jvmPath = jpype.getDefaultJVMPath() ? ? # 開(kāi)啟虛擬機(jī) ? ? jpype.startJVM(jvmPath, '-ea', '-Djava.class.path=%s' % (jarpath)) ? ? # 加載java類(參數(shù)名是java的長(zhǎng)類名) ? ? javaClass = jpype.JClass('scluis.API') ? ? # 調(diào)用類中的方法 ? ? class_file_path = 'D:/study/TD/OpenSourceProject/JFreeChart/source/org/jfree/chart/fx/ChartViewer.java' ? ? # 這里是調(diào)用scluis.API類的靜態(tài)方法getMethods,如果調(diào)用實(shí)例方法,則需要先實(shí)例化java對(duì)象,即javaInstance = javaClass(),在使用實(shí)例調(diào)用 ? ? file_methods_str = javaClass.getMethods(class_file_path) ? ? # 解析返回值,這里的返回值是json數(shù)組 ? ? methods_list = "" ? ? if file_methods_str != "": ? ? ? ? methods_list = json.loads(str(file_methods_str)) ? ? # 關(guān)閉虛擬機(jī) ? ? 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方法是為了測(cè)試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(內(nèi)含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調(diào)用jar包“Class xx not found“問(wèn)題
環(huán)境
- Java 1.8 (64位)
- Python 2.7.9 (32位)
- Jpype 0.5.4.2
- Pycharm
代碼
import jpype from jpype import * # 該目錄下有需要調(diào)用的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()
問(wèn)題
執(zhí)行以上代碼,報(bào)錯(cuò)如下。Class com.abc.EFG not found
檢查點(diǎn)
1.在pak.jar包中有com.abc.EFG
類
2.EFG
依賴的jar包都在同級(jí)目錄下
3.Jpype使用沒(méi)有問(wèn)題:調(diào)用System.out.println
可以打印
jprint = java.lang.System.out.println jprint("xxx") #輸出xxx
試著從環(huán)境上找原因,也許和Java版本有關(guān)。
首先查找pak.jar包的編譯jdk版本
使用以上方法獲得輸出是 52,即對(duì)應(yīng)java 1.8,與本機(jī)Java版本相符。
但是回頭一想其實(shí)在Pycharm中并沒(méi)有配置過(guò)Java的版本。
那么打印一下jvmPath
,獲得的路徑是C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll
,=> 使用的是 jre1.6(32位)。
此時(shí)去Java1.8目錄找,發(fā)現(xiàn)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) # ...
到這里也許有人的問(wèn)題可以解決了,但我的情況是還是報(bào)錯(cuò)…
解決
最后裝了jdk1.8 32位!!!,發(fā)現(xiàn)在client
目錄下有jvm.dll
文件了
再次修改代碼,執(zhí)行通過(guò)。
總結(jié)
原文鏈接:https://blog.csdn.net/weixin_42619772/article/details/122475997
相關(guān)推薦
- 2022-01-09 出現(xiàn)Got permission denied while trying to connect to
- 2022-07-08 Python實(shí)現(xiàn)超快窗口截圖功能詳解_python
- 2022-02-01 微信小程序批量獲取input的輸入值,監(jiān)聽(tīng)輸入框,數(shù)據(jù)同步
- 2022-12-07 R語(yǔ)言隨機(jī)抽樣詳解_R語(yǔ)言
- 2024-03-24 spring boot 3 + spring cloud sleuth 無(wú)法注入Tracer問(wèn)題
- 2022-10-22 Python構(gòu)建簡(jiǎn)單線性回歸模型_python
- 2022-10-05 Python實(shí)現(xiàn)單例模式的五種寫(xiě)法總結(jié)_python
- 2022-09-10 pycharm下載包的時(shí)候出現(xiàn)?no?information?available的解決_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支