Java 8中创建方法引用数组的速记方法是什么?

3
我正在使用Wicket 6 / Java 8,并添加了一些简单的类来利用Java 8的lambda功能(我知道后期的Wicket具有lambda支持,但我们现在无法升级)。我正在创建一个类似于PropertyModel的LambdaModel,希望这将消除需要硬编码表示属性嵌套路径的字符串的需要。
首先,我正在创建一个简单的只读版本。我已经制作了Function接口的可序列化版本来创建以下内容:
public class LambdaModelUtils {
  public static <X,R> IModel<R> ofNested( IModel<X> target, SerializableFunction<?,?>... path ) {
     // creates a model that works through each function in the path in turn
  }
}

我的实现很好,但唯一的问题是以“高效”方式调用此方法会导致编译错误:

IModel<Parent> parentModel = ...
IModel<String> model = LambdaModelUtils.ofNested( parentModel,
                            Parent::getChild, Child::getName );  // Compile time error

我发现唯一的调用该方法的方式是以下代码:

SerializableFunction<Parent,Child> path0 = Parent::getChild;
SerializableFunction<Child,String> path1 = Child::getName;
IModel<String> model = LambdaModelUtils.ofNested( parentModel,
                            path0, path1 );  // works

这个表达有些拙劣,有更好的方式吗?

我在这里查看过,但似乎也不起作用:

List<SerializableFunction> path = Arrays.asList( Parent::getChild, Child::getName );

谢谢


1
只是好奇...为什么在使用方法引用的地方不应该使用lambda表达式? - ernest_k
2
由于SerializableFunction<?,?>需要使用未经检查的转换,因此它并不比使用字符串表示属性更好,即根本没有编译时安全性。 - Holger
2个回答

3

如果您使用这些函数来获取嵌套属性,但实际上并不使用中间结果,我建议您只使用lambda表达式:

public static <X,R> IModel<R> ofNested(IModel<X> target, SerializableFunction<X, R> path)

IModel<Parent> parentModel = ...
IModel<String> model = LambdaModelUtils.ofNested(parentModel, p -> p.getChild().getName());

This works since the target type of the lambda is now known, instead of the generic SerializedFunction<?, ?>, you get SerialiedFunction<X, R> where X = Parent and R = String.


你能分享一下你的 SerializableFunction 接口签名吗? - user3336194

1

我尝试了类似于你的代码。将方法引用转换为函数式接口类型可以解决编译错误:

IModel<String> model =
    LambdaModelUtils.ofNested(parentModel,
                             (SerializableFunction<Parent,Child>) Parent::getChild, 
                             (SerializableFunction<Child,String>) Child::getName);

这不是最美观的解决方案,但至少可以省去声明path0path1变量的需要。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接