java关于引用
引用定义
把已经有的方法拿过来用,可以简化Lambda 表达式。分为静态方法引用、成员方法、构造方法、类名引用
使用说明
- 引用处必须是函数式接口
- 被引用的方法必须已经存在
- 被引用方法的形参和返回值需要跟抽象方法保持一致
- 被引用方法的功能要满足当前需求
引用静态方法
格式:类名::静态方法
范例:Integer::parseInt
对比
// Lambda写法 Functionf = s -> Integer.parseInt(s); // 静态方法引用 Function f = Integer::parseInt;
引用成员方法
分为其他类、本类、父类
引用其他类的成员方法
格式:对象::成员方法
对比
// Lambda写法 Consumerc = s -> System.out.println(s); // 静态方法引用 Consumer c = System.out::println;
引用本类的成员方法
格式:this::方法名
对比
public class Demo { public void show(String s) { System.out.println(s); } public void test() { // Lambda 写法 Consumerc1 = s -> this.show(s); // 方法引用写法 Consumer c2 = this::show; c2.accept("Hello"); } }
引用父类的成员方法
格式:super::方法名
对比
class Father { public void print(String s) { System.out.println("Father: " + s); } } class Son extends Father { public void test() { // Lambda 写法 Consumerc1 = s -> super.print(s); // 方法引用写法 Consumer c2 = super::print; c2.accept("hello"); } }
引用构造方法
格式:类名::new
范例:ArrayList::new
对比
// Lambda写法 Supplier> s = () -> new ArrayList<>(); // 静态方法引用 Supplier
> s = ArrayList::new;
其他
使用类名引用成员方法
格式:类名::成员方法
范例:String::substring
对比
// Lambda写法 BiFunctionf = (s, i) -> s.substring(i); // 静态方法引用 BiFunction f = String::substring; 说明
第一个参数
表示被引用方法的调用者
决定了可以引用哪些类中的方法,换句话说Lambda 的第一个参数类型必须与方法所在类匹配
第二个参数及以后
对应被引用方法的参数列表
如果方法没有参数,那么 Lambda 里除了第一个参数之外就没有其他参数
局限性
不能引用任意类中的任意方法
只能引用第一个参数类型所对应类中的实例方法
方法参数和抽象方法参数必须一一对应
引用数组构造方法
格式:数据类型[]::new
范例:int[]::new
对比
// Lambda写法 Functionf = length -> new int[length]; // 静态方法引用 Function f = int[]::new;










