jpype-python调用java的方法


环境准备:

部署环境准备:
 sed -i.ori '$a export JAVA_HOME=/opt/jdk\nexport PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH\nexport CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib:$JAVA_HOME/lib/tools.jar' /etc/profile
source /etc/profile

java -version
yum install -y python3
mv /etc/yum.repos.d/mcwbak/* /etc/yum.repos.d/
yum install -y python3
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py 
python3 get-pip.py
pip install jpype
tar xf jpype-0.0.tar.gz 
python setup.py install
pip install jpype1

简介: Python 作为一种灵活的软件开发语言在当今被广泛使用。在软件开发过程中,有时需要在 Python 项目中利用既有的 Java 代码,已达到节省时间和开发成本的目的。因此,找到一个 Python 代码调用 Java 代码的桥梁是非常有意义的。 JPype 就是这样的一个工具,利用它可以使 Python 程序方便的调用 Java 代码,从而扩充 Python 语言的能力,弥补 Python 语言的不足。 本文介绍了如何利用 JPype 整合 Python 程序和 Java 程序的一些基本方法。

http://sourceforge.net/projects/jpype/ 目前 JPype 最新的版本为 0.5.4,支持 python 2.5 和 2.6. 本文以 Windows XP 平台,python 2.5.4 为例阐述。

http://www.python.org/download 下载 python 并安装,安装路径选择 C:\Python25\,安装完成后在本地 C 盘应有 C:\Python25 目录,该目录下有 python.exe 文件。 Python 安装完后,双击下载的 JPype 安装文件即可安装 JPype 。

回页首

回页首

应用实例(Password Cipher)

下面我们用一个简单的应用实例来说明如何在 python 代码中调用 Java 类。

Java 类定义

假设我们已用 Java 语言编写了一个类:PasswordCipher,该类的功能是对字符串进行加密和解密。它提供了一个对外的接口 run() 函数,定义如下 :


清单 14. PasswordCipher 定义

public class PasswordCipher { 
    ……
    public static String run(String action, String para){ 
    ……
    } 
……
 } 

run 函数接收两个参数,第一个参数代表所要进行的操作,传入“ encrypt ”表示对第二个参数 para 做加密操作,返回加密结果。如果第一个参数为“ decrypt ”则返回对 para 的解密操作的结果。在 run 函数中有可能会有异常抛出。

Python 代码

我们先将 PasswordCipher.class 存放在目录“ F:\test\cipher ”下,然后用 python 语言编写下面的代码:


清单 15. Python 代码

import jpype 
 from jpype import JavaException 

 jvmPath = jpype.getDefaultJVMPath()           #the path of jvm.dll 
 classpath = "F:\\test\\cipher"                 #the path of PasswordCipher.class 
 jvmArg = "-Djava.class.path=" + classpath 
 if not jpype.isJVMStarted():                    #test whether the JVM is started 
    jpype.startJVM(jvmPath,jvmArg)             #start JVM 
 javaClass = jpype.JClass("PasswordCipher")   #create the Java class 
 try: 
    testString = "congratulations" 
    print "original string is : ", testString 
    #call the run function of Java class 
    encryptedString = javaClass.run("encrypt", testString) 
    print "encrypted string is : ", encryptedString 

    #call the run function of Java class 

    decryptedString = javaClass.run("decrypt", encryptedString) 
    print "decryped string is : ", decryptedString 
 except JavaException, ex: 
    print "Caught exception : ", JavaException.message() 
    print JavaException.stackTrace() 
 except: 
    print "Unknown Error" 
 finally: 
    jpype.shutdownJVM()        #shut down JVM 

运行该程序后得到的结果:


清单 16. 该程序运行的结果是:

original string is :  congratulations 
 encrypted string is :  B0CL+niNYwJLgx/9tisAcQ== 
 decryped string is :  congratulations

原文链接:http://www.pythontip.com/blog/post/4245/