Java 8 new features-4 method reference, new features-4
ForReferenceIn general, we use the object, and the characteristics of object reference are:Different referenced objects can operate on the same content.!
Java 8 method reference defines four formats:
-
- ReferenceStatic MethodClassName: staticMethodName
- ReferenceObject Method: Object: methodName
- ReferenceMethods of Specific Types: ClassName: methodName
- ReferenceConstructor: ClassName: new
- Static Method reference example
/*** Static method reference * @ param <P> parameter type of the referenced method * @ param <R> return type of the referenced method */@ FunctionalInterfaceinterface FunStaticRef <P, r> {public R tranTest (P p);} public static void main (String [] args) {/** static method reference: public static String valueOf * references the String valueOf () method to FunStaticRef # tranTest Method */FunStaticRef <Integer, String> funStaticRef = String: valueOf; String str = funStaticRef. tranTest (10000); System. out. println (str. replaceAll ("0", "9 "));}
- Object MethodReference example
- Example of reference to a specific type of method
- The reference of a specific method is hard to understand. It references a common method, but the reference method is: ClassName: methodName
-
/*** Reference of a specific method * @ param <P> */@ FunctionalInterfaceinterface SpecificMethodRef <P> {public int compare (P p1, P p2 );} public static void main (String [] args) {/** reference of a specific method public int compareTo (String anotherString) * compared with the previous one, objects do not need to be defined before a method is referenced, it can be understood that the object is defined on the parameter! */SpecificMethodRef <String> specificMethodRef = String: compareTo; System. out. println (specificMethodRef. compare ("A", "B"); ConstructorRef <Book> constructorRef = Book: new; Book = constructorRef. createObject ("Java", 100.25); System. out. println (book );}
- Constructor reference example
-
Class Book {private String title; private double price; public Book () {} public Book (String title, double price) {this. price = price; this. title = title ;}@ Override public String toString () {return "Book {" + "title = '" + title +' \ ''+ ", price = "+ price + '}';}}
Public static void main (String [] args) {/** constructor reference */ConstructorRef <Book> constructorRef = Book: new; Book book = constructorRef. createObject ("Java", 100.25); System. out. println (book );}
In general, some new features of Java 8 have not been widely used in the current project, but after learning it, I will not see the code of this new Java 8 feature and will be wrong!