javajava-8method-referenceconstructor-reference

Can Java 8 implement interface on the fly for method reference?


I learn new features of Java 8.

I am playing with different examples and I have found a strange behaviour:

public static void main(String[] args) {       
    method(Test::new);
}
static class Test{
}

private static void method(Supplier<Test> testSupplier){
    Test test = testSupplier.get();
}

This code compiles successfully but I have no idea how it works.

Why is Test::new acceptable as Supplier?

Supplier interface looks very simple:

@FunctionalInterface
public interface Supplier<T> {    
    T get();
}

Solution

  • The Supplier interface has a single (functional) method that:

    Therefore, any method that comply with those two points, comply with the functional contract of Supplier (because the methods will have the same signature).

    Here, the method in question is a method reference. It takes no parameters and returns a new instance of Test. You could rewrite it to:

    method(() -> new Test());
    

    Test::new in syntactic sugar for this lambda expression.