Jython:有没有一种干净的方法来实现带有函数引用的 Java 接口?

发布于 2024-08-25 23:58:27 字数 227 浏览 3 评论 0原文

我知道我可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鲜血染红嫁衣 2024-09-01 23:58:27

从 Jython 2.5.2(beta 2)开始,Jython 函数作为单一方法 Java 接口的实现。来自 http://www.zyasoft .com/pythoneering/2010/09/jython-2.5.2-beta-2-is-released/

Python 函数可以直接传递给采用单一方法接口(例如 Callable 或 Runnable)的 Java 方法。这意味着您现在可以传递回调函数(通常是闭包),而不是将其包装在实现该接口的类中。 Tobias Ivarsson 实现了此功能。

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.

捶死心动 2024-09-01 23:58:27

根据网上的例子,A​​WT/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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文