How to extend a jython class in a java class

java, jython

Solution

You can extend a Jython class in Java such that the result is usable in Jython by creating a Jython class that extends both the Java "subclass" and the Jython "superclass". Let's say you have this Jython class:

class JythonClass(object):
    def get_message(self):
        return 'hello'
    def print_message(self):
        print self.get_message()

You can create your Java class, partially, without extending anything:

public class JavaClass {
    private String message;
    public String get_message() {
        return message;
    }
    protected JavaClass(String message) {
        this.message = message;
    }
}

And then cause the "extending" relationship in Jython:

from javapackage import JavaClass as _JavaClass
from jythonpackage import JythonClass

class JavaClass(_JavaClass, JythonClass):
    pass

Now this will work:

obj = JavaClass('goodbye')
obj.print_message()

If instead you wish to extend a Jython class in Java, and use it like a normal Java class, the easiest way would be to use composition, instead of inheritance:

- create a Java interface for the methods on your Jython class

- make your Jython class extend the Java interface (either by directly modifying your Jython class code, or by something like what I explained above)

- create your Java subclass as implementing the interface, with an instance of the Jython "superclass" as a private field

- any method in your Java subclass that you don't wish to override, just call that method on the private Jython instance

Problem

I would like to extend a jython class in a java class ``` public class JavaClass extends JythonClass ``` how do I import the Jython class? Does it have to be compiled? A link to documentation would be already useful. Example: ``` class JythonClass(threading.Thread): def do(self): print("hallo") ``` -- ``` public class JavaClass extends JythonClass { public void hello() { System.out.print("hallo")} } ```

Original source