auramo
auramo

Reputation: 13357

Jython: is there a clean way to implement a Java interfaces with function references?

I know that I can implement a Java interface with Jython like this:

class MyListener (Listener): 
  def foo(self, event):
    print(str(event))

Python has first-class functions so that seems like an overkill - especially for interfaces with one method. Is there a way to just pass a lambda or function which implements a single method in an interface instead?

Upvotes: 4

Views: 3230

Answers (2)

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

As of Jython 2.5.2 (beta 2), Jython functions work as implementations of single method Java interfaces. From http://www.zyasoft.com/pythoneering/2010/09/jython-2.5.2-beta-2-is-released/ :

Python functions can be directly passed to Java methods that take a single method interface (such as Callable or Runnable). This means you can now pass a callback function, usually a closure, instead wrapping it in a class implementing that interface. Tobias Ivarsson implemented this feature.

Upvotes: 3

Zixnub
Zixnub

Reputation: 11

According to online examples, it is possible for the AWT/Swing Event interface. Simply create a closure with the correct arguments, pass it on and Jython should do the rest. Unfortunately I did not succeed in replicating this behavior for self declared interfaces as I always get a "TypeError: arg can't be coerced" exception.

I, too, would really like to know if it's possible and if so, what I'm doing wrong.

Upvotes: 1

Related Questions