Java 8中静态方法引用的限制 [英] Limits of static method references in Java 8

查看:142
本文介绍了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: the Foo you'd call setBar on, and the String argument you'd pass into setBar.

如果您更改为使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆