I am migrating from Java to Groovy and having an issue 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 doing:
Function f = Bean.&method
Sting s = f.apply new Bean()
But I got an exception, on the f.apply
line:
groovy.lang.MissingMethodException: No signature of method: Bean.method() is applicable for argument types: (Bean) values: [Bean@17483c58]
I know I can do the following to get the 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 with a Function reference. You might have a hierarchy of classes and properties, and to select them, you might do:
property.bind(EasyBind.select(root).select(Root::branch).selectObject(Branch::leaf));
So when any of the values in the tree change, property
get's updated with the correct value.
I am able to replace the Bean.&method
with {bean -> bean.method}
and that works fine. In Java, the Bean::method
is actually an alias-type thing for bean -> bean.method
.
You can use:
MethodClosure f = { it.method }
String s = f()