Groovy 多个实例的方法参考
Groovy method reference for multiple instances
我正在从 Java 迁移到 Groovy 并且遇到方法引用问题。
在 Java 中,我可以这样做:
Function<Bean, String> f = Bean::method;
String s = f.apply(new Bean());
我想在 Groovy 中实现相同的功能。我尝试这样做:
Function f = Bean.&method
Sting s = f.apply new Bean()
但我在 f.apply
行遇到异常:
groovy.lang.MissingMethodException: No signature of method: Bean.method() is applicable for argument types: (Bean) values: [Bean@17483c58]
我知道我可以执行以下操作来获取实例方法的方法引用,但我想获取任何实例的泛型方法。
MethodClosure f = bean.&method
String s = f()
我想用这个来使用EasyBind库。它允许您 select 具有函数引用的 JavaFX 属性。您可能具有 类 和属性的层次结构,对于 select 它们,您可以这样做:
property.bind(EasyBind.select(root).select(Root::branch).selectObject(Branch::leaf));
因此,当树中的任何值发生变化时,property
都会更新为正确的值。
我可以用 {bean -> bean.method}
替换 Bean.&method
并且效果很好。在 Java 中,Bean::method
实际上是 bean -> bean.method
.
的别名类型
您可以使用:
MethodClosure f = { it.method }
String s = f()
我正在从 Java 迁移到 Groovy 并且遇到方法引用问题。
在 Java 中,我可以这样做:
Function<Bean, String> f = Bean::method;
String s = f.apply(new Bean());
我想在 Groovy 中实现相同的功能。我尝试这样做:
Function f = Bean.&method
Sting s = f.apply new Bean()
但我在 f.apply
行遇到异常:
groovy.lang.MissingMethodException: No signature of method: Bean.method() is applicable for argument types: (Bean) values: [Bean@17483c58]
我知道我可以执行以下操作来获取实例方法的方法引用,但我想获取任何实例的泛型方法。
MethodClosure f = bean.&method
String s = f()
我想用这个来使用EasyBind库。它允许您 select 具有函数引用的 JavaFX 属性。您可能具有 类 和属性的层次结构,对于 select 它们,您可以这样做:
property.bind(EasyBind.select(root).select(Root::branch).selectObject(Branch::leaf));
因此,当树中的任何值发生变化时,property
都会更新为正确的值。
我可以用 {bean -> bean.method}
替换 Bean.&method
并且效果很好。在 Java 中,Bean::method
实际上是 bean -> bean.method
.
您可以使用:
MethodClosure f = { it.method }
String s = f()