python调用java API

使用JPype来让python调用java API。

JPype的下载地址:https://pypi.python.org/pypi/JPype1 JPype的帮助文档:http://jpype.readthedocs.io/en/latest/

1、安装:

// 如过已经安装过,请略过这两步  yum install gcc  yum install gcc-c++    // 安装python-devel , 避免报错:error: command 'gcc' failed with exit status 1  yum install python-devel  // 至于pip的安装,请参考:http://blog.csdn.net/xlxxcc/article/details/60958604  pip install jpype1

2、测试代码:

新建test.py, 代码如下:

from jpype import *  startJVM(getDefaultJVMPath(), "-ea")  java.lang.System.out.println("Hello World")  shutdownJVM()

运行test.py,

python test.py

结果如下:

Hello World  JVM activity report     :          classes loaded       : 31  JVM has been shutdown

3、引用jar包:

在com目录下新建文件Test.java

package com;  public class Test {      public String run(String str){          return str;      }  }

编译、打包

// 编译  javac Test.java    // 打包,必须把整个目录(报名和目录名要对应)打包,否则无法访问类。  jar cvf test.jar com

python调用

jarpath = os.path.join(os.path.abspath('.'), 'libs/test.jar')  jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)  Test = jpype.JClass('com.Test')  # 或者通过JPackage引用Test类  # com = jpype.JPackage('com')  # Test = com.Test  t = Test()  res = t.run("a")  print res  jpype.shutdownJVM()