using custom java classes with JPype: package not callable error

6.4k views Asked by At

I'm trying to get a very simple example of using JPype (Version: 0.5.4.6) to instantiate a custom java class from within Python. It loosely follows an example: http://hustleplay.wordpress.com/2010/02/18/jpype-tutorial/ and is related to: JPype Headaches

here's the python code (in /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()

and here's the java code (in /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);
    }
}

compiled using:

javac Test.java

to produce /Users/me/jpypeTest/pkg/Test.class without errors (I have also tried putting Test.class in working directory)

running the python code gives:

> 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 is a mac running Mavericks with:

> 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)

A JPype method for listing the imported java classes would also be very useful

Many thanks for looking at this!

1

There are 1 answers

1
Brian McMaster On BEST ANSWER

The issue appears to be that accessing an attribute of a JPackage class returns a JPackage class when what you really want is a JClass. Changing the testjpype.py to be this worked for me:

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()