1 什么是方法引用(method references)
java 8 添加了一個很熟悉但是又很陌生的符號::。 你也許會看到這樣的代碼
System.out::println
其實就是方法引用(method references)。由于java 8 把方法/函數也作為第一輸入參數。所以你會看到inventory.comparing(Apple::getWeight);這樣“奇怪”的代碼.
2 如何使用方法引用(method references)
其實方法引用是lambda 表達式的一個語法糖。 當lambda只引用一個方法的時候可以通過方法引用(method references)來簡化代碼。
(Apple?a)?->?a.getWeight()??===?Apple::getWeight
()?->?Thread.currentThread().dumpStack()?===?Thread.currentThread()::dumpStack
(str,?i)?->?str.substring(i)?===?String::substring
(String?s)?->?System.out.println(s)?===?System.out::println
3 方法引用的種類
3.1?
static method 靜態方法引用
例子 :Integer::parseInt (parsetInt 是一個靜態方法)
3.2
instance method
例子 :?String::length(length() 是一個實例方法)
3.3
實例對象方法引用
例子 :
Person p = new Person
p::getName (p 是一個實例對象)
轉載于:https://blog.51cto.com/jamesdev/1858767