我正在尝试使用一个非常简单的使用JPype的例子(版本: 0.5.4.6)从Python中实例化一个自定义java类。它 松散地遵循一个例子: http://hustleplay.wordpress.com/2010/02/18/jpype-tutorial/并且是 相关: JPype Headaches
这是python代码(在/Users/me/jpypeTest/testjpype.py中):
from jpype import *
cpopt="-Djava.class.path=%s" % ("/Users/me/jpypeTest")
startJVM(getDefaultJVMPath(),"-ea",cpopt)
print "JVM path:",getDefaultJVMPath()
print "classpath:",cpopt
java.lang.System.out.println("Hello World!!")
testPkg = JPackage('pkg')
Test = testPkg.Test
Test.speak("hi")
shutdownJVM()
这里是java代码(在/Users/me/jpypeTest/pkg/Test.java中):
package pkg;
public class Test {
private String msg;
public Test() {
msg = "nothing so far...";
}
public static void speak(String msg) {
System.out.println(msg);
}
}
编译使用:
javac Test.java
生成/Users/me/jpypeTest/pkg/Test.class而不会出错 (我也尝试将Test.class放在工作目录中)
运行python代码给出:
> python testjpype.py
JVM path: /System/Library/Frameworks/JavaVM.framework/JavaVM
classpath: -Djava.class.path=/Users/me/jpypeTest
Hello World!!
Traceback (most recent call last):
File "testjpype.py", line 9, in <module>
Test.speak("hi")
File "/Users/me/dev/lib/python2.7/site-packages/jpype/_jpackage.py", line 53, in __call__
raise TypeError, "Package "+self.__name+" is not Callable"
TypeError: Package pkg.Test.speak is not Callable
System是一个运行Mavericks的mac:
> java -version
java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)
> javac -version
javac 1.7.0_45
> python --version
Python 2.7.5
> python -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffffffffffff', True)
用于列出导入的java类的JPype方法也非常有用
非常感谢你看到这个!
答案 0 :(得分:1)
问题似乎是,当您真正想要的是JClass时,访问JPackage类的属性会返回JPackage类。更改testjpype.py对我有用:
from jpype import *
cpopt="-Djava.class.path=%s" % ("/Users/me/jpypeTest")
startJVM(getDefaultJVMPath(),"-ea",cpopt)
java.lang.System.out.println("Hello World!!")
Test = JClass('pkg.Test')
Test.speak("hi")
shutdownJVM()