Java 8 new feature method reference
For references, we generally use them on objects, and the characteristic of object reference is that different reference objects can operate on the same piece of content!
Java 8 method reference defines four formats:
Static method reference example
/** * Static method reference* @param <P> Parameter type of reference method* @param <R> Return type of reference method*/@FunctionalInterfaceinterface FunStaticRef<P,R>{ public R tranTest(P p);}public static void main(String[] args) { /* * Static method reference: public static String valueOf * That is, the valueOf() method of String is referenced as FunStaticRef#tranTest method*/ FunStaticRef<Integer, String> funStaticRef = String::valueOf; String str = funStaticRef.tranTest(10000); System.out.println(str.replaceAll("0", "9"));}
Object method reference example
/** * Normal method reference* @param <R> Reference method return type*/@FunctionalInterfaceinterface InstanRef<R>{ public R upperCase();}public static void main(String[] args) { /* * Reference of ordinary methods: public String toUpperCase() * */ String str2 = "i see you"; InstanRef<String> instanRef = str2 :: toUpperCase; System.out.println(instanRef.upperCase());} Example of a specific type method reference
Quotation of a specific method is difficult to understand. It refers to ordinary methods, but the reference method is: ClassName:: methodName
/** * Reference to specific methods* @param <P> */@FunctionalInterfaceinterface SpecificMethodRef<P>{ public int compare(P p1 , P p2);}public static void main(String[] args) { /* * Reference to specific methods public int compareTo(String anotherString) * Compared with the previous method, the object is no longer needed to be defined before the method references, but can be understood as defining the object on the parameters! */ 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);}Example of constructor reference
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) { /* * 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 used in the projects currently in use, but after learning, you won’t see the code of this new features of Java 8 and don’t know what’s wrong!
Thank you for reading, I hope it can help you. Thank you for your support for this site!