最近在做人工智能项目,由于模型训练等主要模块功能用java实现,在做其他功能时,python似乎更方便点,就涉及到了python去调用jar,具体的实现细节做简单记录。
python部分代码如下:
import jpype
from jpype import *
import codecs
# jvmpath = url'home\Java\jre1.8.0_191\bin\server\jvm.dll'
def openjar():
jvmpath = jpype.get_default_jvm_path()
print(jvmpath)
jpype.startJVM(jvmpath,"-Djava.class.path=home\\xxxx-0.0.1-SNAPSHOT-jar-with-dependencies.jar")
jpype.java.lang.System.out.println("hello world")
def get_text(indir):
clasanme = JClass('xxxx.xxxx.classname')
cn = clasanme()
result = cn.getFunctionname(parameter)
print(result)
if __name__ == '__main__':
openjar()
jpype.shutdownJVM()
java打jar包时,得用dependencies的形式,而且java resource下存在properties配置文件时,得一起打入jar包,不能动态修改
具体maven构建时,指定Goals参数:assembly:assembly
pom.xml文件依赖如下:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<archive>
<manifest>
<!-- 我运行这个jar所运行的主类 -->
<mainClass>xxx.xxx.main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>
<!-- 必须是这样写 -->
jar-with-dependencies
</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>