Skip to content Skip to sidebar Skip to footer

Jython, Use Only A Method From Python From Java?

When reading and using this article it assumes that we have a full object definition with class and mapping (proxy) objects from python to java. Is it possible to only import a met

Solution 1:

You can use PyObject.__call__(Object... args) to invoke any callable Python object. You can get the PyFunction representing your function from the java side the same way you example is getting the python employee class.

Alternativeley, you can hide this behind a single method interface on the java side by calling __tojava__(Interface.class) on the function you retrieved from the Python interpreter. Detailed example (actually tested!): python file:

deftmp():
    return"some text"

java:

publicinterfaceI{
    public String tmp();
}

publicstaticvoidmain(String[] args) {
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.exec("from test import tmp");
    PyObject tmpFunction = interpreter.get("tmp");
    System.err.println(tmpFunction.getClass());
    I i = (I) x.__tojava__(I.class);
    System.err.println(i.tmp());

}

output:

class org.python.core.PyFunction
some text

Solution 2:

Importing only a method isn't possible because in Java, methods (or functions) aren't first-class objects, i.e. there's no way to refer to a method without first referring to some class (or interface). Even static methods are enclosed in a class and you refer to them via the class object.

However, you can get fairly close with the solution in introduced in Jython 2.5.2: Jython functions work directly as implementations of single abstract method Java interfaces (see http://www.zyasoft.com/pythoneering/2010/09/jython-2.5.2-beta-2-is-released/). So you can define an interface in Java - it's essential that it contains exactly one method definition:

interfaceMyInterface {
    intmultiply(int x, int y);
}

Plus something like this in Jython:

myFunction = lambda x, y : x * y

and use that as a MyInterface in Java. You still have to use some sort of factory pattern, as described in the article you linked to, to get the Jython function to Java, but something like this works (probably contains errors, but the idea is):

PyObject myFunction = interpreter.get("myFunction"); 
MyInterface myInterface = (MyInterface)myFunction.__tojava__(MyInterface.class);
int x = myInterface.multiply(2, 3); // Should return 6.

Post a Comment for "Jython, Use Only A Method From Python From Java?"