Java 8 Method Reference to non-static method

前端 未结 6 1296
悲哀的现实
悲哀的现实 2020-12-29 10:11

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         


        
6条回答
  •  轮回少年
    2020-12-29 10:40

    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 it worked. But since forEach expects a Consumer 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);
        }
    }
    

    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 invoking the method on that instance can be constructed.

提交回复
热议问题