Java Intellij - 可以替换为方法引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44874857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Intellij - can be replaced with method reference
提问by user
Always when I use lambda expressions like this:
当我使用这样的 lambda 表达式时总是这样:
.map(obj -> foo.makeSomething(obj))
IntelliJ suggests: "Can be replaced with method reference...". And when I try then:
IntelliJ 建议:“可以用方法引用替换...”。当我尝试时:
.map(Foo::makeSomething)
I get the following statement: "Non-static method cannot be referenced from a static context".
我得到以下语句:“不能从静态上下文中引用非静态方法”。
Why Idea suggests me I should use method reference if it's not correct?
为什么 Idea 建议我如果不正确,我应该使用方法引用?
采纳答案by davidxxx
As you write :
当你写:
map(Foo::makeSomething)
the compiler expects one of these two possibilities :
编译器期望以下两种可能性之一:
invoking a
Foo.makeSomething()
instance method on the first parameter of the lambda that has to be so defined as aFoo
.invoking a
Foo.makeSomething()
static method.
Foo.makeSomething()
在 lambda 的第一个参数上调用实例方法,该参数必须如此定义为 aFoo
。调用
Foo.makeSomething()
静态方法。
The first possibility is eliminated by the compiler as the first parameter of the lambda declared obj
is not a Foo
.
编译器消除了第一种可能性,因为声明的 lambda 的第一个参数obj
不是 a Foo
。
And according to your error message, Foo.makeSomething()
is an instance method :
根据您的错误消息,Foo.makeSomething()
是一个实例方法:
Non-static method cannot be referenced from a static context"
不能从静态上下文中引用非静态方法”
So, the second possibility (invoking a Foo.makeSomething()
static method) is not legal either as makeSomething()
is not static.
因此,第二种可能性(调用Foo.makeSomething()
静态方法)也不合法,因为makeSomething()
它不是静态的。
In fact, what you want is applying the makeSomething()
instance method on a variable that doesn't make part of the lambda parameters.
You can do it but you need to use another syntax.
实际上,您想要的是将makeSomething()
实例方法应用于不属于 lambda 参数的变量。
您可以这样做,但您需要使用另一种语法。
Instead of specifying Foo::
, use foo::
.
In this way, the instance method makeSomething()
will be applied on the foo
variable :
而不是指定Foo::
,使用foo::
.
这样,实例方法makeSomething()
将应用于foo
变量:
map(foo::makeSomething)
IntelliJ Intention
智能意图
Note that inspection that reports lambdas which can be replaced with method references can also be automatically refactored by the IDE via an intention.
To do that, set the cursor on the lambda (anywhere on it) and display contextual intentions (Alt+Enter
by default). You should see the intention :
请注意,IDE 也可以通过意图自动重构报告可以替换为方法引用的 lambda 的检查。
为此,请将光标设置在 lambda 上(在其上的任何位置)并显示上下文意图(Alt+Enter
默认情况下)。你应该看到意图:
Replace lambda with method reference
用方法引用替换 lambda
Some screenshots :
一些截图: