python調用java API
- 2020 年 1 月 8 日
- 筆記
使用JPype來讓python調用java API。
JPype的下載地址:https://pypi.python.org/pypi/JPype1 JPype的幫助文檔:http://jpype.readthedocs.io/en/latest/
1、安裝:
// 如過已經安裝過,請略過這兩步 yum install gcc yum install gcc-c++ // 安裝python-devel , 避免報錯:error: command 'gcc' failed with exit status 1 yum install python-devel // 至於pip的安裝,請參考:http://blog.csdn.net/xlxxcc/article/details/60958604 pip install jpype1
2、測試程式碼:
新建test.py, 程式碼如下:
from jpype import * startJVM(getDefaultJVMPath(), "-ea") java.lang.System.out.println("Hello World") shutdownJVM()
運行test.py,
python test.py
結果如下:
Hello World JVM activity report : classes loaded : 31 JVM has been shutdown
3、引用jar包:
在com目錄下新建文件Test.java
package com; public class Test { public String run(String str){ return str; } }
編譯、打包
// 編譯 javac Test.java // 打包,必須把整個目錄(報名和目錄名要對應)打包,否則無法訪問類。 jar cvf test.jar com
python調用
jarpath = os.path.join(os.path.abspath('.'), 'libs/test.jar') jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath) Test = jpype.JClass('com.Test') # 或者通過JPackage引用Test類 # com = jpype.JPackage('com') # Test = com.Test t = Test() res = t.run("a") print res jpype.shutdownJVM()