JPype (Python): importing folder of jar's

2019-08-02 06:05发布

问题:

i am using JPype in order to work with java classes in python. I have a folder that contains multiple self-written .jar files.

I know how to import multiple .jar's on the long way:

...
CLASSPATH = "/path/to/jars/first.jar:/path/to/jars/second.jar"
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % CLASSPATH)
MYLIB= jpype.JPackage("org").mylib
MyClass = MYLIB.MyClass
myObj = MyClass()

This works fine, but i think there might be a better way.

I already tried this:

CLASSPATH = "/path/to/jars/*.jar"

and this:

CLASSPATH = "/path/to/jars/*"

In both cases following error occurs:

user@user:~/path/to/python/$ python test.py
Traceback (most recent call last):
  File "test.py", line 23, in <module>
    myObj = MyClass()
  File "/usr/local/lib/python2.7/dist-packages/JPype1-0.6.2-py2.7-linux-x86_64.egg/jpype/_jpackage.py", line 60, in __call__
    raise TypeError("Package {0} is not Callable".format(self.__name))
TypeError: Package org.mylib.MyClass is not Callable

My Question:

Is there any way to easily import a folder that contains multiple .jar's in JPype?

回答1:

You can join the list of jar files with Python code without hardcoding

f'{str.join(":", ["path/to/jars/"+name for name in os.listdir("path/to/jars")])}'