Convert a Python function to Java anonymous class

Fri 29 April 2011
  • 手艺 tags:
  • java
  • jython
  • python published: true comments: true

When calling Java with Jython, anonymous inner class might be an issue because there is no such equivalent in Python.

In GUI programming, jython made additional effort on AWT event processing. You can pass a python function as some types of event listener.
[cc lang="python"]
def change_text(event):
print 'Clicked!'

button = JButton('Click Me!', actionPerformed=change_text)
frame.add(button)
[/cc]

Described in the Definitive Guide of Jython:

This works because Jython is able to automatically recognize events in Java code if they have corresponding addEvent()* and *removeEvent() methods. Jython takes the name of the event and makes it accessible using the nice Python syntax as long as the event methods are public.

However, it does not work with Runnable, Callable and many other interfaces designed for anonymous usage.

To solve the incompatibility, I created a small decorator that converts Python function to a Java object.

Thanks to python's dynamic magic, we can create class in runtime and assign modified method to a particular instance. The conversion is performed once the function loaded. Also, you can pass something as arguments to constructor.

With anonymous_class decorator, the example above can be written as:
[cc lang="python"]
from javax.swing import JButton, JFrame
from java.awt.event import ActionListener

frame = JFrame('Hello, Jython!',
defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
size = (300, 300)
)

@anonymous_class(ActionListener, "actionPerformed")
def change_text(dummy, event):
print 'Clicked!'

button = JButton('Click Me!', actionPerformed=change_text)
frame.add(button)
frame.visible = True
[/cc]