Now it's a constructor reference. The method reference in the previous article sensuously specified that the implementation of the functional IF abstract method should be a specific method. Is it an image that you can specify the method and the constructor as specific?
As with the last time, prepare some functional IFs as appropriate. SampleBean is a dedicated return value bean prepared for methodA of SampleFunctionalIF3, and SampleBeanExt is a bean that just extends it and creates a default constructor. getter and setter are omitted.
@FunctionalInterface
public interface SampleFunctionalIF<T> {
String methodA(T object);
}
@FunctionalInterface
public interface SampleFunctionalIF2 {
String methodA();
}
@FunctionalInterface
public interface SampleFunctionalIF3 {
SampleBean methodA(String A, String B);
}
public class SampleBean {
private String val1;
private String val2;
}
public class SampleBeanExt extends SampleBean {
SampleBeanExt(String param1, String param2) {
this.setVal1(param1);
this.setVal2(param2);
System.out.println("SampleBeanExt constructor called");
}
}
So, the following is trying to execute these.
public class ConstructorRef {
public static void main(String[] args) {
//With argument (String)in the case of
//New String at the timing when the abstract method methodA specified by the functional IF is called("xyz")Is called
System.out.println("-----Example 1-----");
SampleFunctionalIF<String> sample = String::new;
System.out.println(sample.methodA("xyz"));
//No arguments (String)in the case of
//New String at the timing when the abstract method methodA specified by the functional IF is called()Is called
//The size is 0 because it is an empty string
System.out.println("-----Example 2-----");
SampleFunctionalIF2 sample2 = String::new;
String s2 = sample2.methodA();
System.out.println(s2.length());
//With 2 arguments
//At the timing when the abstract method methodA specified by the functional IF is called
// new SampleBeanExt("hello","world")Is called
System.out.println("-----Example 3-----");
SampleFunctionalIF3 sample3 = SampleBeanExt::new;
SampleBean bean = sample3.methodA("hello", "world");
System.out.println("1:" + bean.getVal1());
System.out.println("2:" + bean.getVal2());
}
}
And the execution result
-----Example 1-----
xyz
-----Example 2-----
0
-----Example 3-----
SampleBeanExt constructor called
1:hello
2:world
It seems like it's just after doing a method reference. However, I can't think of any use for this.
Recommended Posts