美文网首页
07 方法引用

07 方法引用

作者: 张力的程序园 | 来源:发表于2020-04-15 16:49 被阅读0次

本小节继续方法引用,即方法可以作为参数被传递,其与lambda联合使用 ,方法引用可以使语言的构造更加紧凑简洁,减少冗余代码。

1、方法引用的分类

  • 构造器引用
    Class::new对应lambda表达式:(args) -> new 类名(args)
  • 静态方法引用
    Class::static_method对应lambda表达式:(args) -> 类名.static_method(args)
  • 对象方法引用
    Class::method对应lambda表达式:(inst,args) -> 类名.method(args)
  • 实例方法引用
    instance::method对应lambda表达式:(args) -> instance.method(args)

2、测试代码


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;

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

        //1构造器使用:   Class::new
        MethodReference mr = MethodReference.create(MethodReference::new);
        //lambda表达式写法
        MethodReference mr1 = MethodReference.create(()->new MethodReference());

        List<MethodReference> list = Arrays.asList(mr);
        //2静态方法引用 Class::static_method
        list.forEach(MethodReference::test1);
        //lambda表达式写法
        list.forEach((methodReference)->MethodReference.test1(methodReference));

        //3对象方法引用 Class::method
        list.forEach(MethodReference::test3);

        //4实例方法引用  instance::method
        MethodReference mr2 = MethodReference.create(MethodReference::new);
        list.forEach(mr2::test2);
        //lambda表达式写法
        list.forEach((methodReference)->mr2.test2(methodReference));

        //另外,我们也可以将 System.out::println 方法作为静态方法来引用。
        List<String> names = new ArrayList<String>();
        names.add("java");
        names.add("python");
        names.add("cpp");
        names.forEach(System.out::println);
    }

    public interface Student<T> {
        T get();
    }

    public static MethodReference create(Supplier<MethodReference> call) {
        return call.get();
    }

    public static void test1(MethodReference methodReference) {

        System.out.println("test1");
    }

    public void test2(MethodReference methodReference) {
        System.out.println("test2");
    }

    public void test3() {
        System.out.println("test3");
    }
}

以上就是jdk8中的方法引用。

相关文章

  • 07 方法引用

    本小节继续方法引用,即方法可以作为参数被传递,其与lambda联合使用 ,方法引用可以使语言的构造更加紧凑简洁,减...

  • 2020-07-04【方法引用】

    体验方法引用 方法引用符 引用方式

  • Java8——方法引用和构造器引用

    方法引用和构造器引用 方法引用 若Lambda体中的内容已经有方法实现过了,我们可以使用方法引用(方法引用是Lam...

  • 双冒号方法引用

    类别使用形式静态方法引用类名 :: 静态方法名实例方法引用对象名(引用名) :: 实例方法名类方法引用类名 :: ...

  • Java中的双冒号::是什么玩意?有这个语法?

    简洁 方法引用 Optional 可选值 一:简洁 方法引用分为三种,方法引用通过一对双冒号:: 来表示,方法引用...

  • 3.Java8新特性 - 方法引用与构造器

    一.方法的引用 方法引用是用来直接访问类或者实例的已经存在的方法或者构造方法。方法引用提供了一种引用而不执行方法的...

  • jdk8 方法引用

    方法引用 方法引用可看作一个“函数指针” function pointer 方法引用分为4类 1,类名::静态方法...

  • 方法引用

    1.什么是方法引用 方法引用是java8中特定情况下简化lambada表达式的一种语法糖,这里的特定情况是指当调用...

  • 方法引用

    方法引用(Method References) 声明:java8新特性系列为个人学习笔记,参考地址点击这里,侵删!...

  • 方法引用

    1.1 方法引用体验 方法引用出现的原因 在使用Lambda表达式的时候,我们实际上传递进去的代码就是一种解决方案...

网友评论

      本文标题:07 方法引用

      本文链接:https://www.haomeiwen.com/subject/mrxkphtx.html