All of the examples in the Jython documentation here require that the the Python class import the corresponding Java interface, for example:

# A python module that implements a Java interface to
# create a building object
from org.jython.book.interfaces import BuildingType

class Building(BuildingType):
    def __init__(self, name, address, id):
        self.name = name
        self.address = address
        self.id = id
        ...

I would rather not couple my Python code to my Java code. Is there a way I can instantiate the Python class from Java without modifying it to point to a Java interface?

1

There are 1 best solutions below

0
On

The best answer I've been able to come up with so far has been to implement Java wrappers around each Python class I want to instantiate. Each Java wrapper holds a PyObject, but provides statically typed access to its fields, e.g.

public class PeanutWrapper{
  private PyObject pyObj;

  public String getKind(){
    return pyObj.__findattr__("kind");
  }

  ...
}

It works, but it's not as elegant a solution as I'd hoped to find.