0

I have a Java library and I have to build a Python wrapper to it.

I am using py4j, and it's pretty easy to get any instance and any class, complete with method.

The problem is that the type of an object doesn't correspond to its class.

From python:

>>> gw = JavaGateway()
>>> a_circle = gw.jvm.com.geometry.Circle(15)
>>> a_circle.getDiameter()
30
>>> type(a_circle)
<class 'py4j.java_gateway.JavaObject'>

This is almost ok for basic usage, but what if I want to create custom constructors? Should I subclass the JavaObject class? Or it's better to create my classes from scratch and for every method and constructor invoke the corresponding Java method?

Any suggestion for a good way to achieve it? Should i try something different than py4j? Thank you!

EDIT: for example, I have to wrap a Java class that has 3 methods, one of those methods takes an array as parameter, so I have to inject some code in order to convert.

class Service:
    def __init__(self, javaService):
    '''
    Create a new instance of Service, assigning Java methods as attributes.
    Accepts a working instance of Service from Java
    This constructor is not meant to be called by the user.
    '''

    self.subscribe = javaService.subscribe
    self.unsubscribe = javaService.unsubscribe

    def publish(values):
        '''
        Wraps the java implementation of this method, converting the list of value from a Python iterable to a Java list.
        '''
        global java_gateway
        parameterValues = ListConverter().convert(values, java_gateway._gateway_client)
        return javaService.publish(values)
    self.publish = publish

This works, but I am doing only when it is necessary. If the class just works directly, I am not writing anything to wrap it.

  • Hi, can you give an example of what you are trying to achieve, e.g., what the end code should look like? Specifically, what do you mean by "but what if I want to create custom constructors"? – Barthelemy May 10 '18 at 12:11
  • @Barthelemy I have edited the question with an example. Actually there isn't much to say, the code works, I was just wondering if there is a template, a good practice for wrapping. – Federico Picetti Jun 15 '18 at 14:36
  • Have you tried [JPype](https://jpype.readthedocs.io/)? It is a very mature approach for wrapping Java classes into Python classes, as Pythonically as possible. – ctrueden Nov 22 '22 at 17:52

0 Answers0