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

I know that I can implement the Java interface with Jython as follows:

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

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

+4
source share
2 answers

As with Jython 2.5.2 (beta 2), Jython functions as an implementation of one-level 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 use the same method interface (for example, Callable or Runnable). This means that now you can pass a callback function that usually closes, instead transferring it to a class that implements this interface. Tobias Ivarsson implemented this feature.

+3
source

According to online examples, this is possible for the AWT / Swing Event interface. Just create a closure with the correct arguments, pass it, and Jython should do the rest. Unfortunately, I was not able to reproduce this behavior for self-declared interfaces, since I always get the exception "TypeError: arg cannot be forced".

I would also like to know if this is possible, and if so, what am I doing wrong.

+1
source

Source: https://habr.com/ru/post/1304965/


All Articles