开发者

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 t开发者_如何学Chat 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜