JPype documentation
JPype is an effort to allow python programs full access to java class libraries. This is achieved not through re-implementing Python, as Jython/JPython has done, but rather through interfacing at the native level in both virtual machines. Eventually, it should be possible to replace Java with python in many, though not all, situations. JSP, Servlets, RMI servers and IDE plugins are good candidates.
下載地址:https://pypi.python.org/pypi/JPype1
幫助文檔:http://jpype.readthedocs.io/en/latest/
1.測試代碼
from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("Hello World")
shutdownJVM()
2.引用jar包
在com目錄下新建文件Test.java
package com;
public class Test {
public String run(String str){
return str;
}
}
編譯
javac Test.java
打包
【論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()