简体   繁体   English

使用py4j将python列表转换为java数组

[英]convert python list to java array using py4j

as the title say, I want to convert a list of string in python into a java array.正如标题所说,我想将python中的字符串列表转换为java数组。 After that, I will pass the java array to a java method taking varargs arguments.之后,我会将 java 数组传递给采用 varargs 参数的 java 方法。 And I use py4j.我使用 py4j。 In java, I have this method:在java中,我有这个方法:

public static void MyJavaMethod(String ...myStrings){
//my method instructions
}

And in python, the only thing I could do is to convert my python list to JavaList but the trouble is that we can't pass Javalist to a method taking varargs arguments(only array):在 python 中,我唯一能做的就是将我的 python 列表转换为 JavaList 但问题是我们无法将 Javalist 传递给采用可变参数参数(仅数组)的方法:

from py4j.java_collections import SetConverter, MapConverter, ListConverter
from py4j.java_gateway import JavaGateway
mypythonlist=['string1', 'string2']
gateway = JavaGateway()
java_list = ListConverter().convert(mypythonlist, gateway._gateway_client)
# MyJavaArray=???
gateway.entry_point.MyJavaMethod(MyJavaArray)

So, I need to know how to convert python list to a java array using py4j.所以,我需要知道如何使用 py4j 将 python 列表转换为 java 数组。 In java, we can perform it using .toArray() but I don't know how to do it from python.在 java 中,我们可以使用.toArray()执行它,但我不知道如何从 python 中执行它。

I found a methode from github that solve my problem:我从 github 上找到了一个方法来解决我的问题:

from py4j.java_collections import SetConverter, MapConverter, ListConverter
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
mypythonlist=['string1', 'string2']
object_class = gateway.jvm.java.lang.String
MyJavaArray = gateway.new_array(object_class, len(mypythonlist))
for i in range(len(mypythonlist)):
    my_array[i]=mypythonlist[i]
gateway.entry_point.MyJavaMethod(MyJavaArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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