Jython:有没有一种干净的方法来实现带有函数引用的 Java 接口?
我知道我可以使用 Jython 实现 Java 接口,如下所示:
class MyListener (Listener):
def foo(self, event):
print(str(event))
Python 具有一流的函数,因此这似乎有点过头了 - 特别是对于具有一种方法的接口。有没有办法只传递一个在接口中实现单个方法的 lambda 或函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 Jython 2.5.2(beta 2)开始,Jython 函数作为单一方法 Java 接口的实现。来自 http://www.zyasoft .com/pythoneering/2010/09/jython-2.5.2-beta-2-is-released/:
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/ :
根据网上的例子,AWT/Swing Event接口是可以的。只需使用正确的参数创建一个闭包,将其传递下去,Jython 就会完成剩下的工作。不幸的是,我没有成功地为自我声明的接口复制这种行为,因为我总是收到“TypeError:arg不能被强制”异常。
我也很想知道这是否可能,如果可以,我做错了什么。
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.