什么是方法引用
通过类名或对象名引用已经存在的方法来简化lambda表达式。
方法引用的格式
通过类名或对象名引用
类名::方法名 或 对象名::方法名
方法引用的四种类型
静态方法引用: 类名::静态方法
对象方法引用: 对象名::成员方法
构造方法引用: 类名::new
特定类型的实例方法引用(了解) 类名::非静态方法
方法引用的原理
创建了一个类实现了函数式接口,并重写了接口中的抽象方法,在重写的方法中调用了被引用的方法。
创建该实现类对象。
方法引用的好处
简化lambda表达式
重复利用已经存在方法
示例:
@FunctionalInterface
public interface NumberConversion {
String convert(int num);
}
public class Test03 {
public static void main(String[] args) {
decToHex(999, Integer::toHexString);
decToHex(999,(nc)->Integer.toHexString(nc));
}
static void decToHex(int num,NumberConversion nc){
String convert = nc.convert(num);
System.out.println(convert);
}
}
输出结果:
3e7
3e7