相关疑难解决方法(0)

Java 8中静态方法引用的限制

我正在尝试使用方法引用来捕获方法调用,并且遇到了一些限制.这很好用:

<T> void capture(Function<T, ?> in) {
}

private interface Foo {
  String getBar();
} 

capture(Foo::getBar);
Run Code Online (Sandbox Code Playgroud)

但是,如果我将Foo.setBar的签名更改为以下内容:

private interface Foo {
  void setBar(String bar);
}

capture(Foo::setBar);
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

Cannot make a static reference to the non-static method setBar(String) from the type MyTest.Foo

我不清楚限制是什么.理想情况下,我想使用方法引用来捕获标准setter上的调用.有没有办法做到这一点?

java java-8 method-reference

7
推荐指数
2
解决办法
3153
查看次数

标签 统计

java ×1

java-8 ×1

method-reference ×1