1

how can i iterate on a Jython PyList and cast or convert my contained object to java.lang.String ?

in this old tutorial, it is done by using __ tojava __ like :

(EmployeeType)employeeObj.__tojava__(EmployeeType.class);

i suppsoe this may be something like :

 PyList pywords = pythonFactoryCreatedObject.pythonMethodReturningPyList()

 int count = pywords.__len__();
 for (int idx = 0 ; idx < count ; idx++) {
     PyObject obj = pywords.__getitem__(idx);

    //here i do not know how to have a kind of 'String word = pywords[idx]' statement

    //System.out.println(word);
 }

is it also possible to have :

  • a conversion from PyList to java Array or List ? so that the construct 'for (String word : mylist) { }' can be used ?

  • i will have the same trouble with simple python dictionary mapping to an adequate java object, what will be the best mapping ?

Is there a tutorial doc on the java part usage of Jython ? i'm quite ok with python, but new to Java and Jython, and i found only documentation on the Java usage from Jython while i need to embed a Python module inside a Java framework...

best

1 Answer 1

2

PyList actually implements java.util.List<Object>, so you can use that directly from Java side. If you fill with strings, its elements will be PyString (or maybe PyUnicode). So:

List pywords = pythonFactoryCreatedObject.pythonMethodReturningPyList();
for (Object o : pyList){
  String string = ((PyString) o).getString();
  //whatever you want to do with it 
}

or

List pywords = pythonFactoryCreatedObject.pythonMethodReturningPyList()
for (Object o : pyList){
  String string = ((PyObject) o).__toJava__(String.class);
  //whatever you want to do with it 
}

whichever you find clearer.

Edit: here's the standard doc on embedding Jython into Java. The better way to use Jython from Java would be to implement Java interfaces from Jython and manipulate the interfaces from Java, but it seems you're working with an existing Python codebase, so that wouldn't work without some changes.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your useful explanations ! i did not get the point on the use of __ toJava __ and your answer help me to understand better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.