Tuesday, September 18, 2018

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

Answer



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




  • does not take any parameters;

  • returns an object.



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...