Java 8中静态方法引用的限制 [英] Limits of static method references in Java 8
问题描述
我正在尝试使用方法引用来捕获方法调用,并且遇到了一些限制。这很好用:
I'm trying to use method references to capture method invocations and am hitting some limitations. This works fine:
<T> void capture(Function<T, ?> in) {
}
private interface Foo {
String getBar();
}
capture(Foo::getBar);
但如果我将Foo.setBar的签名更改为以下内容:
But if I change the signature of Foo.setBar to something like this:
private interface Foo {
void setBar(String bar);
}
capture(Foo::setBar);
我收到错误消息:
无法从MyTest.Foo类型对非静态方法setBar(String)进行静态引用
它不是向我明确限制是什么。理想情况下,我想使用方法引用来捕获标准setter上的调用。有没有办法做到这一点?
It's not clear to me what the restriction is. Ideally I'd like to use method references to capture invocations on standard setter. Is there any way to do this?
推荐答案
这里有两个问题:
- 你正在使用
功能
,它必须返回一些东西。setBar
不会返回任何内容。 -
功能
只需输入一个,但你有两个输入:Foo
你打电话给setBar
on ,以及你传入setBar
的String
参数。
- You're using
Function
, which has to return something.setBar
doesn't return anything. Function
only takes a single input, but you've got two inputs: theFoo
you'd callsetBar
on, and theString
argument you'd pass intosetBar
.
如果您更改为使用 BiConsumer
而是(具有 void
返回它输入正常:
If you change to use BiConsumer
instead (which has a void
return type and two inputs) it works fine:
static <T, U> void capture(BiConsumer<T, U> in) {
}
你可以重载你的捕获
方法以获得两个签名:
You can overload your capture
method to have both signatures:
static <T, U> void capture(BiConsumer<T, U> in) { }
static <T> void capture(Function<T, ?> in) { }
然后使用两个方法引用:
and then use both method references:
capture(Foo::setBar);
capture(Foo::getBar);
这篇关于Java 8中静态方法引用的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!