python调用java的方法-JPype的简单使用

今天来说下,python调用java的方法,有些时候,数据处理比较麻烦,像加解密,可能之前的技术栈用java,或者对接的业务方提供了java版的api,但是公司使用的是技术栈是python,平台也是python,不方便使用java编写,并且也不好将java代码用python代码再实现一遍时,就需要用到python调用java了。下面来看看具体如何实现呢?

介绍

python作为一种很灵活的脚本开发语言,在现在被广泛使用,但是在服务端,相比java较弱,于是如何补足这个短板,节省开发时间,提高效率呢,就需要找到一个python调用java的方法,于是jpype被开发出来,专门调用java类,获取类的方法,创建java对象实例,完成需求。
官方网站点击这里

安装

pip install jpype1

简单使用

来看看简单的hello world程序,直接python命令行了:

(base) [chenzuoli@chenzuolis-MacBook /Users/chenzuoli]$python
Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import jpype
>>> jvmPath = jpype.getDefaultJVMPath()
>>> jpype.startJVM(jvmPath)
>>> jpype.java.lang.System.out.println( "hello world!" )
hello world!
>>> jpype.shutdownJVM()
>>>

jpype提供的startJVM()函数的作用就是启动java虚拟机,后续的java代码就会在java虚拟机里执行,并且虚拟机里的对象在程序运行完成后,销毁,虚拟机会自动释放关闭掉,也可以手动关闭,关闭后,虚拟机内的对象就无法使用了。

startJVM()方法是可以传参数的,来看看官方给出的源码:

startJVM(jvm, *args)

有2个参数:
1.jvm:jvmPath,可以获取默认的jvm path

jpype.getDefaultJVMPath()

2.args:启动jvm指定的一些参数

-agentlib:libname[=options] 
 -classpath classpath 
 -verbose 
 -Xint

判断jvm是否已经启动:

jpype.isJVMStarted()

这个方法在程序比较复杂的时候做判断使用。

注意:

如果jvm被关闭,再次启动会出现报错:

python调用java类的方法 python能调用java吗_jvm

如果jvm已经启动了,也不能再次启动。

实际使用,获取java类

通过将jar添加到java classpath里,然后指定主类,就可以获得java对象了,然后就可以调用他的属性和方法了:

def getJVMClass():
    # java jar位置,被调用的jar
    jarpath = "/mnt/pet/photography-0.0.1-SNAPSHOT.jar"

    # 获取java path
    jvmpath = jpype.getDefaultJVMPath()

    # 启动jvm,如果已经启动了,再次启动会报错,所以try except一下
    # 其中参数convertStrings设置为false,意思是java的string不转换为python的string类型。不设置为false的话,会报警warning:
    # Deprecated: convertStrings was not specified when starting the JVM. The default
    # behavior in JPype will be False starting in JPype 0.8. The recommended setting
    # for new code is convertStrings=False. The legacy value of True was assumed for
    # this session. If you are a user of an application that reported this warning,
    # please file a ticket with the developer.
    try:
        startJVM(jvmpath, "-ea", "-Djava.class.path=%s" % jarpath, convertStrings=False)
    except:
        pass
    JC = JClass('pet.photography.PetApplication')
    instance = JC()
    return instance

参考官方文档:

python调用java类的方法 python能调用java吗_python_02

参考官网:点这里