Python调用Java程序(打包与JPype)

Python调用Java程序(打包与JPype)

java程序打包jar(maven)

当程序不引用第三方依赖时

1
2
3
# c:创建新档案 v:详细输出 f:指定档案文件名
# example.jar为指定的文件名 xxx.class为需要打包的类,按需添加
jar -cvf example.jar example1.class example2.class

或使用maven的package指令

当程序引用第三方依赖时

方法一:

使用开发软件的打包功能

vscode左下角JAVA PROJECTS栏上点击第二个按钮(Export Jar),接着选择主类以及需要的类和依赖等,就可以得到包含第三方依赖的jar包

方法二:

使用插件

在pom.xml中添加maven-assembly-plugin插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<project>
<build>
<pluginManagement>
<plugins>
<!-- 添加插件,使jar包包含依赖 -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>

</pluginManagement>
</build>
</project>

接着在项目的目录下执行命令,在target文件夹中得到包含依赖的jar包

1
mvn clean compile assembly:single

How can I create an executable/runnable JAR with dependencies using Maven?

maven将第三方依赖打进jar包_将依赖打入jar包_兵工厂三剑客的博客-CSDN博客

Executable Jar with depedencies

jpype

jpype是一个python模块,用于从python中提供对java的完全访问

JPype documentation

python与java位数一致

首先确保使用的python和java位数一样(都是64位或都是32位)

在cmd中输入pythonjava -version即可查看

安装

1
pip install jpype1

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import jpype

# jar包路径
jar_path = "example.jar"
# 启动java虚拟机(虚拟机路径,模式,jar包路径)
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" %jar_path)
# 加载类
exampleClass = jpype.JClass('com.Example')
# 类实例化
exampleInstance = exampleClass(0, 0)
# 执行函数
test = exampleInstance.test("hello")
print(test)
# 关闭虚拟机
jpype.shutdownJVM()

Python调用Java程序(打包与JPype)
https://wangaaayu.github.io/blog/posts/189cd634/
作者
WangAaayu
发布于
2023年6月17日
更新于
2023年8月3日
许可协议