Today I learned the new usage of constructors, static methods, and methods under java8, and shared the source code, so everyone can learn together import lombok.AllArgsConstructor; import lombok.Builder; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor @Builder public class Person { private String firstName; private String lastName; }
public class SomeThing { String startWith(String s){ return String.valueOf(s.charAt(0)); } }
@FunctionalInterface public interface PersonFactory<P extends Person> { P create(String firstName,String lastName); }
@FunctionalInterface public interface IConvert<F,T> { T convert(F from); }
public class IConvertTest { /** * Method and constructor references * java8 allows you to pass the method and constructor references through the keyword::. */ @Test public void staticMethodQuote(){ IConvert<String,Integer> converter = Integer::parseInt; int converted = converter.convert("1233"); System.out.println(converted); } @Test public void quoteObjectMethod (){ SomeThing something = new SomeThing(); IConvert<String,String> convert =something::startWith; convert.convert("abc"); } // reference constructor @Test public void quoteConstructorMethod() { // Instead of using the usual manually implemented factory classes, all the work is united by using a constructor // Create a reference to the Person constructor via Person::new. //The java compiler automatically selects the correct constructor to match the function signature of PersonFactory.create. PersonFactory<Person> factory = Person::new; Person p = factory.create("zhuge", "xx"); System.err.println(p); } }