Java 8新特性方法引用
對(duì)于引用來說我們一般都是用在對(duì)象,而對(duì)象引用的特點(diǎn)是:不同的引用對(duì)象可以操作同一塊內(nèi)容!
Java 8的方法引用定義了四種格式:
- 引用靜態(tài)方法 ClassName :: staticMethodName
- 引用對(duì)象方法: Object:: methodName
- 引用特定類型方法: ClassName :: methodName
- 引用構(gòu)造方法: ClassName :: new
靜態(tài)方法引用示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/** * 靜態(tài)方法引用 * @param <P> 引用方法的參數(shù)類型 * @param <R> 引用方法的返回類型 */ @FunctionalInterface interface FunStaticRef<P,R>{ public R tranTest(P p); } public static void main(String[] args) { /* * 靜態(tài)方法引用: public static String valueOf * 即將String的valueOf() 方法引用為 FunStaticRef#tranTest 方法 */ FunStaticRef<Integer, String> funStaticRef = String::valueOf; String str = funStaticRef.tranTest( 10000 ); System.out.println(str.replaceAll( "0" , "9" )); } <br> |
對(duì)象方法引用示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/** * 普通方法引用 * @param <R> 引用方法返回類型 */ @FunctionalInterface interface InstanRef<R>{ public R upperCase(); } public static void main(String[] args) { /* * 普通方法的引用: public String toUpperCase() * */ String str2 = "i see you" ; InstanRef<String> instanRef = str2 :: toUpperCase; System.out.println(instanRef.upperCase()); } |
特定類型方法引用示例
特定方法的引用較為難理解,本身其引用的是普通方法,但是引用的方式卻為: ClassName :: methodName
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/** * 特定方法的引用 * @param <P> */ @FunctionalInterface interface SpecificMethodRef<P>{ public int compare(P p1 , P p2); } public static void main(String[] args) { /* * 特定方法的引用 public int compareTo(String anotherString) * 與之前相比,方法引用前不再需要定義對(duì)象,而是可以理解為將對(duì)象定義在了參數(shù)上! */ 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); } |
構(gòu)造方法引用示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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) { /* * 構(gòu)造方法引用 */ ConstructorRef<Book> constructorRef = Book :: new ; Book book = constructorRef.createObject( "Java" , 100.25 ); System.out.println(book); } |
總的來說Java 8一些新的特性在目前做的項(xiàng)目中還未大量使用,但是學(xué)習(xí)一下,到時(shí)也不至于看到這種Java 8新特性的代碼而不知所錯(cuò)!
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:http://www.cnblogs.com/MPPC/p/5356262.html