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.