Java中的方法引用

1、概述

大家好,我是欧阳方超。
Java8中引入了不少新特性,其中就包括函数式接口(Functional Interface)和Lambda表达式(Lambda expressions),而理解函数式接口和Lambda表达式是掌握方法引用(Method references)的基础。
方法引用是一种特殊形式的Lambda表达式,使用方法引用可以通过引用现有的方法来创建简单的Lambda表达式。
一共有四种形式的方法引用:

类型方法引用
静态方法引用Class::static_method
特定对象的实例方法引用instance::method
某个类型的任意对象的实例方法的引用Cass::method
构造方法引用Class::new

下面逐一看一下这几类方法引用的使用。

2、方法引用

2.1、静态方法引用

静态方法引用的语法为,类名::静态方法名,下面是一个使用静态方法引用的例子,方法引用其实是返回了函数式接口InterfaceOne的对象,跟Lambda表达式挺像,只不过方法引用这里所引用的方法名可以跟函数式接口中声明的函数名不同。

@FunctionalInterface
interface InterfaceOne {
    void testMethod();
}

class StaticMethod {
    public static void staticMethodTest() {
        System.out.println("static method test");
    }
}

public class MethodReference {
    public static void main(String[] args) {
        //下面方法引用其实是返回了函数式接口InterfaceOne的对象
        InterfaceOne interfaceOne = StaticMethod::staticMethodTest;
        interfaceOne.testMethod();
    }
}

2.2、实例方法引用

引用实例方法的语法,instance::instanceMethodName,即实例::实例方法名,实例方法引用与静态方法引用很像,只不过一个是通过实例进行引用一个是通过类进行引用。

@FunctionalInterface
interface InterfaceOne {
    void testMethod();
}

class StaticMethod {
    public void staticMethodTest() {
        System.out.println("static method test");
    }
}

public class MethodReference {
    public static void main(String[] args) {
        InterfaceOne interfaceOne = new StaticMethod()::staticMethodTest;
        interfaceOne.testMethod();
    }

}

2.3、某个类型的任意对象的实例方法的引用

public class MethodReference {
    public static void main(String[] args) {

        ArrayList<String> lastNames = new ArrayList<>();
        lastNames.add("zhang");
        lastNames.add("wang");
        lastNames.add("li");

        Collections.sort(lastNames, String::compareTo);

        lastNames.forEach(System.out::println);
    }

}

2.4、构造方法引用

构造方法引用的语法,Class::new,

@FunctionalInterface
interface InterfaceOne {
    void testMethod();
}

class StaticMethod {
    public StaticMethod() {
        System.out.println("static method constructor");
    }
}

public class MethodReference {
    public static void main(String[] args) {
        InterfaceOne interfaceOne = StaticMethod::new;
        interfaceOne.testMethod();
    }

}

3、总结

当想要创建的Lambda体已经有实现方法时,这时可以使用方法引用。Lambda是匿名类的简化写法,方法引用是Lambda的简化写法,如同Lambda表达式创建了函数式接口的实例一样,方法引用也是创建了某个函数式接口的实例。
我是欧阳方超,把事情做好了自然就有兴趣了,如果你喜欢我的文章,欢迎点赞、转发、评论加关注。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值