gpt4 book ai didi

java - JPype 将参数传递给 Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:50 26 4
gpt4 key购买 nike

我有一个 java 外观类,我试图从 python 访问,所以我决定使用 JPype。我的外观类只有一个构造函数(无默认值)和四个参数

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

在初始化类的新实例时,我似乎无法获得正确的类型。我尝试的一切都给出了同样的错误:

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

我知道 JPype 正在运行。我已经尝试了几种包装器组合来以正确的形式获取数据,但没有成功。

相关代码:

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) 不会匹配列表。您必须使用 jpype.java.util.ArrayList()(或任何实现 List 的东西)。

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

所以你的代码看起来像这样:

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

关于java - JPype 将参数传递给 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13637614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com