关键字::
用法
通过 ::
关键字来访问类的构造方法,对象方法,静态方法。
存在类something
class Something {
// constructor methods
Something() {}
Something(String something) {
System.out.println(something);
}
// static methods
static String startsWith(String s) {
return String.valueOf(s.charAt(0));
}
// object methods
String endWith(String s) {
return String.valueOf(s.charAt(s.length()-1));
}
void endWith() {}
}
定义接口(必须要用 functional interface 来接收,否则编译错误)
@FunctionalInterface
interface IConvert<F, T> { // 传参类型为F,返回类型为T
T convert(F form);
}
@FunctionalInterface 注解要求接口有且只有一个抽象方法
访问静态方法:
// static methods
IConvert<String, String> convert = Something::startsWith;
String converted = convert.convert("123");
访问对象方法
// object methods
Something something = new Something();
IConvert<String, String> converter = something::endWith;
String converted = converter.convert("Java");
访问构造方法
// constructor methods
IConvert<String, Something> convert = Something::new;
Something something = convert.convert("constructors");
总结:
我们可以把类Something中的方法static String startsWith(String s){…}、String endWith(String s){…}、Something(String something){…}看作是接口IConvert的实现,因为它们都符合接口定义的那个“模版”,有传参类型F以及返回值类型T。
比如构造方法Something(String something),它传参为String类型,返回值类型为Something。注解@FunctionalInterface保证了接口有且仅有一个抽象方法,所以JDK能准确地匹配到相应方法。
复杂示例
把方法当做参数传入stream内部
旧式用法:
public class AcceptMethod {
public static void printValur(String str){
System.out.println("print value : "+str);
}
public static void main(String[] args) {
List<String> al = Arrays.asList("a","b","c","d");
for (String a: al) {
AcceptMethod.printValur(a);
}
//下面的for each循环和上面的循环是等价的
al.forEach(x->{
AcceptMethod.printValur(x);
});
}
}
加入::
public class MyTest {
public static void printValur(String str){
System.out.println("print value : "+str);
}
public static void main(String[] args) {
List<String> al = Arrays.asList("a", "b", "c", "d");
al.forEach(AcceptMethod::printValur);
//下面的方法和上面等价的
Consumer<String> methodParam = AcceptMethod::printValur; //方法参数
al.forEach(x -> methodParam.accept(x));//方法执行accept
}
}