Converting Python lists to Java arrays

1,275 views
Skip to first unread message

Daniel Barker

unread,
Nov 7, 2017, 1:03:00 PM11/7/17
to Jep Project
Hi,

So far Jep has been very good at automatically converting between Python & Java types for me. Now I'm trying to call a Java function which expects as an argument a String[]. In Python I am giving it a list of strs, however I get the following error

TypeError: Error converting parameter 2: Expected [Ljava.lang.String; but received a list.

I had hoped Jep would automatically detect the list contained strings and convert it to an array of Java strings. I know this is complicated by the fact a list in Python need not contain entries with the same data type. (Going in the other direction works fine)

Are there plans to implement this? 

How can I work around this?

Thanks,
Dan

Ben Steffensmeier

unread,
Nov 7, 2017, 6:38:38 PM11/7/17
to Jep Project
In version 3.7 we only have code to automatically convert a python list to an ArrayList. So the obvious solution would be to change your java code to accept a List instead of a String[]. There are probably some good reason you can't change the java so on the python side of things you could convert your list to a jarray before passing it in like this:

>>> pylist = ["a", "b", "c"]
>>> from jep import jarray
>>> from java.lang import String
>>> jarr = jarray(len(pylist), String)
>>> for i in range(len(pylist)):
...     jarr[i] = String(pylist[i])
...
>>> from java.util import Arrays
>>> Arrays.toString(jarr)
'[a, b, c]'

That isn't beautiful but it should get the job done.

I also just implemented the automatic conversion of lists and tuples to arrays in the dev_3.8 branch. It would be helpful if you could check that out and make sure it works intuitively as you expect. If neither of the other solutions works for you will have to work off the dev branch or a custom branch until the release of 3.8.

Ben

Daniel Barker

unread,
Nov 8, 2017, 4:48:41 AM11/8/17
to Jep Project
I checked out the dev_3.8 branch and it works fine, it automatically converts as expected. Thanks for the good work on Jep!
Reply all
Reply to author
Forward
0 new messages