Method and Constructor Reference
Method Reference
1.
Method Reference is an abbreviated syntax used with lambda expressions for invoking a method.
Double colon operator (::) is used to represent a method reference.
The syntax for the same is:
ClassName::MethodName
2. A method reference can be used to point the following types of methods:
Static method
Instance method
Constructors using new operator (TreeSet::new)
eg:
public class newfeatures {
public static void main(String[] args) {
Converter<String, Integer> converter = (a) -> Integer.valueOf(a);
Integer aa = converter.convert("1234");
System.out.println(aa);
String bb = "31234";
System.out.println(Integer.valueOf(bb));
Converter<String, Integer> test1 = Integer::valueOf;
Integer cc = test1.convert("0987");
System.out.println(cc);
Something st1 = new Something();
// Converter<String, String> test2 = st1::startsWith;
Converter<String, String> test2 = st1::endWith;
String st2 = test2.convert("Java");
System.out.println(st2);
}
}
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
}
class Something {
String startsWith(String s) {
return String.valueOf(s.charAt(0));
}
String endWith(String s) {
return String.valueOf(s.charAt(s.length()-1));
}
}
Constructor Reference
class Person{
String firstName;
String lastName;
Person(){}
Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
interface PersonFactory<P extends Person>{
P create(String firstName, String lastName);
}
public void main(String[] avgs){
PersonFactory<Person> pF = Person::new;
Person p = pF.create("Peter", "Parker");
}
Instead of implementing the factory manually, we glue everything together via constructor reference.
We create a reference to the Person constructor via Person::new. The Java compiler automatically choose the right constructor by matching the signature of PersonFactory.create.
Last updated
Was this helpful?