Java 8方法参考非静态方法 [英] Java 8 Method Reference to non-static method
问题描述
为什么这不起作用?我得到编译器错误无法对非静态方法打印静态引用...
Why this doesn't work? I get compiler error "Cannot make static reference to the non static method print..."
public class Chapter3 {
public void print(String s) {
System.out.println(s);
}
public static void main(String[] args) {
Arrays.asList("a", "b", "c").forEach(Chapter3::print);
}
}
推荐答案
无论如何无论您使用方法引用,lambda表达式还是普通方法调用,实例方法都需要适当的实例来进行调用。该实例可以由函数调用提供,例如, if forEach
期望 BiConsumer< Chapter3,String>
它有效。但由于 forEach
在您的情况下需要 Consumer< String>
,因此没有的实例第3章
的范围。您可以通过将 Chapter3.print
更改为 static
方法或通过提供实例作为目标来轻松解决此问题。方法调用:
Regardless of whether you use method references, lambda expressions or ordinary method calls, an instance method requires an appropriate instance for the invocation. The instance may be supplied by the function invocation, e.g. if forEach
expected a BiConsumer<Chapter3,String>
it worked. But since forEach
expects a Consumer<String>
in your case, there is no instance of Chapter3
in scope. You can fix this easily by either, changing Chapter3.print
to a static
method or by providing an instance as target for the method invocation:
public class Chapter3 {
public void print(String s) {
System.out.println(s);
}
public static void main(String[] args) {
Arrays.asList("a", "b", "c").forEach(new Chapter3()::print);
}
}
这里是的结果新的Chapter3()
,一个新的第3章
实例,将被捕获用于 print $的方法引用c $ c>方法和
Consumer< String>
可以构造调用该实例上的方法。
Here, the result of new Chapter3()
, a new instance of Chapter3
, will be captured for the method reference to its print
method and a Consumer<String>
invoking the method on that instance can be constructed.
这篇关于Java 8方法参考非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!