To implement a Java interface in Python so it can be passed to Java, subclass PythonJavaClass.
Requirements:
- Define
__javainterfaces__: A list of Java interfaces in 'path/to/Interface' format. - Use the
@java_method(signature) decorator on Python methods to map them to the interface. - Limitations: You can only implement interfaces (you cannot subclass Java objects) and you cannot implement static methods/fields. You must keep a reference to the Python object alive as long as Java is using it.
Class Loaders (__javacontext__):
'system' (default): Used for standard Java API interfaces.'app': Required on Android if you are implementing an interface that is part of your own APK/application code.
from jnius import PythonJavaClass, java_method
class PythonListIterator(PythonJavaClass):
__javainterfaces__ = ['java/util/ListIterator']
def __init__(self, collection, index=0):
super(PythonListIterator, self).__init__()
self.collection = collection
self.index = index
@java_method('()Z')
def hasNext(self):
return self.index < len(self.collection.data) - 1
@java_method('()Ljava/lang/Object;')
def next(self):
obj = self.collection.data[self.index]
self.index += 1
return obj