# 安装 pip install jpype1
# -*- coding:utf-8 -*- from jpype import * ''' 调用标准代码 ''' if __name__ == "__main__": # 启动java虚拟机 startJVM(getDefaultJVMPath(), "-ea") # 调用println函数 java.lang.System.out.println("hello python java") # 关闭虚拟机 shutdownJVM()
- 调用自定义代码
public class JPypeDemo{ public String say(String user){ return "java say: " + user; } public int calc(int a, int b){ return a + b; }}
# 编译 javac JPypeDemo.java # 打包 jar cvf JPypeDemo.jar JPypeDemo.class
- python调用
# -*- coding:utf-8 -*- from jpype import * import os if __name__ == "__main__": # 启动java虚拟机 # 注意使用了-D选项指定了jar的目标位置 startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % (os.getcwd() + "/JPypeDemo.jar")) # 加载自定义的java class JDClass = JClass("JPypeDemo") jd = JDClass() # 获取java标准库打印函数 jprint = java.lang.System.out.println # 调用自定义class中的函数,并输出返回值 jprint(jd.say("deeptest")) jprint(jd.calc(1, 4)) # 关闭虚拟机 shutdownJVM()