Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 279
andres.santana Avatar asked Oct 02 '14 20:10

andres.santana


2 Answers

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);
    }
}

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.

like image 102
Holger Avatar answered Sep 28 '22 01:09

Holger


Just in case if you are trying to apply an instance method from the same object where your code runs

Arrays.asList("a", "b", "c").forEach(this::print);
like image 34
Sergey Shcherbakov Avatar answered Sep 28 '22 02:09

Sergey Shcherbakov