Method and Constructor References

The above example code can be further simplified by utilizing static method references:

  1. Converter<String,Integer> converter =Integer::valueOf;
  2. Integer converted = converter.convert("123");
  3. System.out.println(converted);// 123

Java 8 enables you to pass references of methods or constructors via the :: keyword. The above example shows how to reference a static method. But we can also reference object methods:

  1. classSomething{
  2. String startsWith(String s){
  3. returnString.valueOf(s.charAt(0));
  4. }
  5. }
  1. Something something =newSomething();
  2. Converter<String,String> converter = something::startsWith;
  3. String converted = converter.convert("Java");
  4. System.out.println(converted);// "J"

Let’s see how the :: keyword works for constructors. First we define an example class with different constructors:

  1. classPerson{
  2. String firstName;
  3. String lastName;
  4. Person(){}
  5. Person(String firstName,String lastName){
  6. this.firstName = firstName;
  7. this.lastName = lastName;
  8. }
  9. }

Next we specify a person factory interface to be used for creating new persons:

  1. interfacePersonFactory<P extendsPerson>{
  2. P create(String firstName,String lastName);
  3. }

Instead of implementing the factory manually, we glue everything together via constructor references:

  1. PersonFactory<Person> personFactory =Person::new;
  2. Person person = personFactory.create("Peter","Parker");

We create a reference to the Person constructor via Person::new. The Java compiler automatically chooses the right constructor by matching the signature of PersonFactory.create.