简体   繁体   中英

JPype Passing args to Java

I have a java facade class I'm trying to access from python so I decided to use JPype . My facade class only has one constructor (no default) with four args

public facade(String a, String b, List<String> c, List<String> d){
    ...
}

I can't seem to get the types correct when initializing a new instance of the class. Everything I try gives the same error:

File ".../main.py", line 34, in __init__
    facadeinstance = Facade(jpype.JString(s1), jpype.JString(s2),jpype.JArray(jpype.java.lang.String, 1)(s3), jpype.JArray(jpype.java.lang.String, 1)(s4))
File "/usr/local/lib/python2.7/dist-packages/jpype/_jclass.py", line 79, in _javaInit
    self.__javaobject__ = self.__class__.__javaclass__.newClassInstance(*args)
RuntimeError: No matching overloads found. at src/native/common/jp_method.cpp:121

I know JPype is working. I've tried several combinations of wrappers to get the data in the right form with no luck.

Relevant code:

import jpype

s1 = "something"
s2 = "something else"
s3 = ["something in a list"]
s4 = ["Something else in a list"]

jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=" + JavaJarDir)
myLib = jpype.JPackage('myLib')
Facade = myLib.Facade # class loads fine, resources printed to stdout
# The error occurs on the next line
FacadeInstance = Facade(jpype.JString(s1), jpype.JString(s2), jpype.JArray(jpype.java.lang.String, 1)(s3), jpype.JArray(jpype.java.lang.String, 1)(s4))
jpype.shutdownJVM()

JArray(JString) won't match List. You have to use jpype.java.util.ArrayList() (or anything that implements List).

myArray = ["A", "B", "C"]
myList = jpype.java.util.ArrayList()
for s in myArray:
    myList.add(s)

So your code will look like that:

import jpype

s1 = "something"
s2 = "something else"
s3 = ["something in a list"]
s4 = ["Something else in a list"]

jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=" + JavaJarDir)

# Import Java library and class
myLib = jpype.JPackage('myLib')
Facade = myLib.Facade

# Prepare List<String> arguments
arg3 = jpype.java.util.ArrayList()
for s in s3:
    list3.add(s)
arg4 = jpype.java.util.ArrayList()
for s in s4:
    list4.add(s)

FacadeInstance = Facade(jpype.JString(s1), jpype.JString(s2), arg3, arg4)

jpype.shutdownJVM()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM