Using / Creating Python Objects with Jython
HI,
says I have a Java B interface, something like this. B.java:
public interface B { String FooBar(String s); }
and I want to use it with Python class D that inherits from B, like this. D.py:
class D(B):
def FooBar(s)
return s + 'e'
So how do I get an instance of D in java? I'm sorry I asked a question like this n00b, but the Jython doc sucks / is partially disabled.
+2
source to share
1 answer
The code for your example is above. You also need to change your FooBar implementation to accept the self argument, since it is not a static method.
For this example, you need to have jython.jar in your classpath to compile and run.
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class Main {
public static B create()
{
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from D import D");
PyObject DClass = interpreter.get("D");
PyObject DObject = DClass.__call__();
return (B)DObject.__tojava__(B.class);
}
public static void main(String[] args)
{
B b = create();
System.out.println(b.FooBar("Wall-"));
}
}
For more details see the chapter on Jython and Java Integration in The Jython Book
+3
source to share