4

我正在尝试使用 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 方法也非常有用

非常感谢您看这个!

4

1 回答 1

4

问题似乎是当您真正想要的是 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()
于 2017-11-06T17:30:56.817 回答