Groovy method reference for multiple instances

I am migrating from Java to Groovy and have a problem with method references.

In Java, I could do this:

Function<Bean, String> f = Bean::method;
String s = f.apply(new Bean());

I want to implement the same functionality in Groovy. I tried:

Function f = Bean.&method
Sting s = f.apply new Bean()

But I got an exception on the line f.apply:

groovy.lang.MissingMethodException: No signature of method: Bean.method() is applicable for argument types: (Bean) values: [Bean@17483c58]

I know that I can do the following to get a method reference for an instance method, but I want to get a generic method for any instance.

MethodClosure f = bean.&method
String s = f()

I want to use this to use the EasyBind library. It allows you to select a JavaFX property using a function reference. You can have a hierarchy of classes and properties, and you can select them:

property.bind(EasyBind.select(root).select(Root::branch).selectObject(Branch::leaf));

Therefore, when any of the values ​​in the tree changes, it is propertyupdated with the correct value.

Bean.&method {bean -> bean.method}, . Java Bean::method bean -> bean.method.

+4
1

:

MethodClosure f = { it.method }
String s = f()
+2

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


All Articles