方法引用,顾名思义,可以将方法作为参数传递(想想对象引用,想想C++的函数指针),但java中有类似功能的也就是java8中lambda表达式了,说白了,方法引用就是lambda表
达式的一种特殊形式。实际上方法引用是lambda表达式的一种语法糖。
使用方法
方法引用使用一对冒号 ::
方法引用分为四种:
- 构造器引用(类名::new):它的语法是Class::new,或者更一般的Class< T >::new
- 静态方法引用(类名::静态方法名):它的语法是Class::static_method
- 特定类的任意对象的方法引用(类名::实例方法名 ):它的语法是Class::method
- 特定对象的方法引用(对象::实例方法名):它的语法是instance::method
静态方法引用
替换lambda表达式模板
from
(args) -> Class.staticMethod(args)
to
Class::staticMethod
样例
public class Main {
public static void main(String[] args) {
//
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <5 ; i++) {
System.out.println("我是匿名內部类"+i);
}
}
}).start();
new Thread(()->{
for (int i = 0; i <5 ; i++) {
System.out.println("我是lambda表达式"+i);
}
}).start();
//静态方法引用
new Thread(Test2::run).start();
}
}
class Test2{
public static void run(){
for (int i=0;i<5;i++){
System.out.println("我是方法引用 "+i);
}
}
}
就是将其它类的静态方法引用过来,而且这个静态方法的参数个数类型需要和你在此写lambda表达式时的参数个数类型对应。感觉就是lambda表达式的替换,提高了代码复用。
在此,大家大概能理解方法引用大概是怎么回事,这四种方法引用大致差不多,但干的事都是一样的。
特定对象的方法引用
替换lambda表达式模板
from
(args) -> obj.instanceMethod(args)
to
obj::instanceMethod
public class Main {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <5 ; i++) {
System.out.println("我是匿名內部类"+i);
}
}
}).start();
new Thread(()->{
for (int i = 0; i <5 ; i++) {
System.out.println("我是lambda表达式"+i);
}
}).start();
//静态方法引用
new Thread(Test2::run).start(); //类名加方法名
//对象实例方法引用
Test2 test2 = new Test2();
new Thread(test2::run2).start(); //对象名加方法名
}
}
class Test2{
public static void run(){
for (int i=0;i<5;i++){
System.out.println("我是方法引用 "+i);
}
}
public void run2(){
for (int i=0;i<5;i++){
System.out.println("我是对象实例方法引用 "+i);
}
}
}
这个和静态方法引用差不多,好理解,静态的用类名调用就行了,非静态的实例化后再调用就行了。
特定类的任意对象的方法引用
这个可能不会像上面两个那么直观
首先它的基本转换格式如下:
from
(obj, args) -> obj.instanceMethod(args)
to
ObjectType::instanceMethod
- 我们使用实例的类型而非实例本身
- 参数隐式传递
样例
public class People {
public double calculateWeight() {
double weight = 0;
// Calculate weight
return weight;
}
public List<Double> calculateAllWeight(List<People> l, Function<People, Double> f) {
List<Double> results = new ArrayList<>();
for (People s : l) {
results.add(f.apply(s));
}
return results;
}
}
class PeopleClient {
public static void main(String[] args) {
List<People> list = new ArrayList<>();
People p = new People();
// Using an anonymous class
p.calculateAllWeight(list, new Function<People, Double>() {
@Override
public Double apply(People people) {// The object
return people.calculateWeight();// The method
}
});
// Using a lambda expression
p.calculateAllWeight(list, people -> people.calculateWeight());
// Using a method reference
p.calculateAllWeight(list, People::calculateWeight);
}
}
在这个例子中,我们没有给方法传递任何参数,关键在于对象的实例是lambda表达式的一个参数,我们通过实例的类型来完成对实例方法的引用。
下面是另一个例子,在这个例子中,我们向方法引用中传递了两个参数。
//java中有一个Function接口可以接收一个参数,BiFunction接口接受两个参数,没有接受三个参数的,所以我们自定义一个TriFunction
interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
//然后定义一个类,接收两个参数,并且有一个返回值
class Sum {
Integer doSum(String s1, String s2) {
return Integer.parseInt(s1) + Integer.parseInt(s1);
}
}
//用匿名类实现TriFunction,来包装doSum()
TriFunction<Sum, String, String, Integer> anonymous =
new TriFunction<Sum, String, String, Integer>() {
@Override
public Integer apply(Sum s, String arg1, String arg2) {
return s.doSum(arg1, arg2);
}
};
System.out.println(anonymous.apply(new Sum(), "1", "4"));
//使用lambda表达式来包装
TriFunction<Sum, String, String, Integer> lambda =
(Sum s, String arg1, String arg2) -> s.doSum(arg1, arg2);
System.out.println(lambda.apply(new Sum(), "1", "4"));
//使用方法引用
TriFunction<Sum, String, String, Integer> mRef = Sum::doSum;
System.out.println(mRef.apply(new Sum(), "1", "4"));
- 第一个参数是要执行的方法的实例对象
- 第二、三个参数是传递的其他参数
- 最后一个参数是要执行的方法的返回值类型
构造器引用
如何替换lambda表达式?如下:
from
(args) -> new ClassName(args)
to
ClassName::new
无参构造
// Using an anonymous class
Supplier<List<String>> s = new Supplier() {
public List<String> get() {
return new ArrayList<String>();
}
};
List<String> l = s.get();
// Using a lambda expression
Supplier<List<String>> s = () -> new ArrayList<String>();
List<String> l = s.get();
// Using a method reference
Supplier<List<String>> s = ArrayList::new;
List<String> l = s.get();
有参构造
// Using a anonymous class
BiFunction<String, String, Locale> f = new BiFunction<String, String, Locale>() {
public Locale apply(String lang, String country) {
return new Locale(lang, country);
}
};
Locale loc = f.apply("en","UK");
// Using a lambda expression
BiFunction<String, String, Locale> f = (lang, country) -> new Locale(lang, country);
Locale loc = f.apply("en","UK");
// Using a method reference
BiFunction<String, String, Locale> f = Locale::new;
Locale loc = f.apply("en","UK");
如果有三个及以上的参数的构造函数,则必须创建自己的函数接口。引用构造函数与引用静态方法非常相似,区别在于构造函数“方法名称”是new。
总结
如果使用了方法引用之后能让代码变的更加整洁,就使用它。实际使用中,一种使用方式是将代码包裹在一个方法中,而非使用一个单独的类或者lambda表达式,然后使用方法引用的方式进行调用。方法引用常用于java8的另一种新特性Streams中,而基于方法引用的设计模式也会更加具有拓展性。
方法引用简化了lambda表达式,lambda表达式简化了匿名内部类。