方法引用其实是lambda表达式的一个简化写法,所引用的方法其实是lambda表达式的方法体实现。
语法:
1
2
3
4
5
6
7
| ObjectReference::methodName
如果是静态方法,ClassName::methodName。如 Object ::equals
如果是实例方法,Instance::methodName。如Object obj=new Object();obj::equals;
构造函数,ClassName::new
|
例子
1
2
3
4
| @FunctionalInterface
interface Converter<F, T> {
T convert(F from);
}
|
使用常规的Lambda表达式:
1
2
3
| Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
Integer converted = converter.convert("1024");
System.out.println(converted); // 1024
|
静态方法引用:
1
2
3
| Converter<String, Integer> converter = Integer::valueOf;
Integer converted = converter.convert("1024");
System.out.println(converted); // 1024
|
对象方法引用:
1
2
3
4
5
6
7
8
9
10
| public class Something {
String startsWith(String s) {
return String.valueOf(s.charAt(0));
}
}
Something something = new Something();
Converter<String, String> converter = something::startsWith;
String converted = converter.convert("Java");
System.out.println(converted); // J
|
构造函数引用:
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
| class Person {
String firstName;
String lastName;
Person() {}
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName
+ "]";
}
}
@FunctionalInterface
interface PersonFactory<P extends Person> {
P create(String firstName, String lastName);
}
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Peter", "Parker");
System.out.println(person);//Person [firstName=Peter, lastName=Parker]
|
通过Person::new来创建一个Person类构造函数的引用。Java编译器会自动地选择合适的构造函数来匹配PersonFactory.create函数的签名,并选择正确的构造函数形式。
1
2
| //自动匹配Person类的 Person(String firstName, String lastName)构造函数。
PersonFactory<Person> personFactory = Person::new;
|
参考资料:
http://winterbe.com/posts/2014/03/16/java-8-tutorial/