mysql 双冒号_jdk8新特性之双冒号 :: 用法及详解
jdk8的新特性有很多,最亮眼的當屬函數(shù)式編程的語法糖,本文主要講解下雙冒號::的用法。
概念
類名::方法名,相當于對這個方法閉包的引用,類似js中的一個function。比如:
Function?func?=??String::toUpperCase;
(Function在java.util.function包下,也是jdk8新加入的類,同級目錄下有很多函數(shù)式編程模型接口,比如Consumer/Predicate/Operator等)
func相當于一個入?yún)⒑统鰠⒍紴镾tring的函數(shù),可以直接
func.apply("abc")
接收一個參數(shù),返回一個結(jié)果("ABC")。也可以用于代替下面的Lambda表達式:
List?l?=?Arrays.asList("a","b","c");
l.stream().map(s?->?s.toUpperCase());
l.stream().map(func);
下面自定義一個函數(shù)式接口
public?class?MyConsumer?implements?Consumer{
@Override
public?void?accept(String?s){
System.out.println(s);
}
}
下面這倆種寫法等價:
List?l?=?Arrays.asList("a","b","c");
l.forEach(new?MyConsumer<>());
l.forEach(s?->?System.out.println(s));
但是,這種寫法卻不行,編譯失敗:
l.forEach(MyConsumer::accept);
因為MyConsumer的accept方法不是靜態(tài)的,如果想使用這個方法,需要一個實例,還需要一個入?yún)?#xff0c;共倆個參數(shù)。而List.forEach中需要的是consumer類型,相當于s -> {...},只有一個參數(shù)。
下面詳細分析雙冒號使用的各種情況
新建一個類,里面聲明四個代表各種情況的方法:
public?class?DoubleColon?{
public?static?void?printStr(String?str){
System.out.println("printStr?:?"?+?str);
}
public?void?toUpper(){
System.out.println("toUpper?:?"?+?this.toString());
}
public?void?toLower(String?str){
System.out.println("toLower?:?"?+?str);
}
public?int?toInt(String?str){
System.out.println("toInt?:?"?+?str);
return?1;
}
}
把它們用::提取為函數(shù),再使用:
Consumer?printStrConsumer?=?DoubleColon::printStr;
printStrConsumer.accept("printStrConsumer");
Consumer?toUpperConsumer?=?DoubleColon::toUpper;
toUpperConsumer.accept(new?DoubleColon());
BiConsumer?toLowerConsumer?=?DoubleColon::toLower;
toLowerConsumer.accept(new?DoubleColon(),"toLowerConsumer");
BiFunction?toIntFunction?=?DoubleColon::toInt;
int?i?=?toIntFunction.apply(new?DoubleColon(),"toInt");
非靜態(tài)方法的第一個參數(shù)為被調(diào)用的對象,后面是入?yún)ⅰlo態(tài)方法因為jvm已有對象,直接接收入?yún)ⅰ?/p>
再寫一個方法使用提取出來的函數(shù):
public?class?TestBiConsumer?{
public?void?test(BiConsumer?consumer){
System.out.println("do?something?...");
}
}
下面這倆種傳入的函數(shù)是一樣的:
TestBiConsumer?obj?=?new?TestBiConsumer();
obj.test((x,y)?->?System.out.println("do?something?..."));
obj.test(DoubleColon::toLower);
總結(jié)
用::提取的函數(shù),最主要的區(qū)別在于靜態(tài)與非靜態(tài)方法,非靜態(tài)方法比靜態(tài)方法多一個參數(shù),就是被調(diào)用的實例。
來源:https://my.oschina.net
/wangbo888/blog/1942354
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的mysql 双冒号_jdk8新特性之双冒号 :: 用法及详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql触发器 while循环_mys
- 下一篇: xa协议 mysql_分布式事务XA实现