For reference , we are generally used in objects, and object reference is characterized by: different reference objects can manipulate the same piece of content !
The method reference for Java 8 defines four formats:
-
- reference static method span> classname   :: staticmethodname
- reference object Method : object::
- reference specific type method : classname :: methodname
- construction method : classname :: New
- static method Reference Example
/*** Static method reference *@param<P> parameter types for reference methods *@param<R> return type of a reference method*/@FunctionalInterfaceInterfaceFunstaticref<p,r>{ PublicR trantest (P p);} Public Static voidMain (string[] args) {/** Static method reference: public static string ValueOf * The string's ValueOf () method is referred to as the Funstaticref#trantest method */Funstaticref<integer, string> funstaticref =string::valueof; String Str= Funstaticref.trantest (10000); System.out.println (Str.replaceall ("0", "9"));}
- Object MethodsReference Example
- Example of a specific type method reference
- A reference to a particular method is difficult to understand, and itself refers to a common method, but the way it is quoted is: ClassName:: MethodName
-
/*** References to specific methods *@param<P>*/@FunctionalInterfaceInterfaceSpecificmethodref<p>{ Public intCompare (P P1, p p2);} Public Static voidMain (string[] args) {/** Reference to a specific method public int compareTo (String anotherstring) * Compared to previous methods, the method reference no longer needs to define the object, but can be understood to define the object on the parameter! */Specificmethodref<String> Specificmethodref =String:: compareTo; System.out.println (Specificmethodref.compare ("A", "B")); Constructorref<Book> constructorref = Book::New; Book Book= Constructorref.createobject ("Java", 100.25); SYSTEM.OUT.PRINTLN (book);}
- Constructor Method Reference Example
-
classbook{PrivateString title; Private DoublePrice ; PublicBook () {} PublicBook (String title,DoublePrice ) { This. Price =Price ; This. title =title; } @Override PublicString toString () {return"book{" + "title=" + title + ' \ ' + ", price=" + Price + '} '; }}
Public Static voidMain (string[] args) {/** Construction Method Reference*/Constructorref<Book> constructorref = Book::New; Book Book= Constructorref.createobject ("Java", 100.25); SYSTEM.OUT.PRINTLN (book);}
In General, some of the new features of Java 8 have not been used extensively in the projects currently being done, but learning about it will not be enough to see the code for this new Java 8 feature without knowing what is wrong!
Java 8 new Features-4 method references