zoukankan      html  css  js  c++  java
  • java8-方法引用

    1.通过对象名引用成员方法
    如果一个类中已经存在了一个成员方法:

    public class MethodRefObject {
      public void printUpperCase(String str) {
        System.out.println(str.toUpperCase());
      }
    }

    函数式接口仍然定义为:

    @FunctionalInterface
    public interface Printable {
        void print(String str);
    }    

    那么当需要使用这个printUpperCase 成员方法来替代Printable 接口的Lambda的时候,已经具有了
    MethodRefObject 类的对象实例,则可以通过对象名引用成员方法,代码为:

    public class Demo04MethodRef {
    private static void printString(Printable lambda) {
        lambda.print("Hello");
    }
    public static void main(String[] args) {
         //Lambda
        printString(s-> {
            MethodRerObject dro=new MethodRerObject();
            dro.printUpperCaseString(s);
        }); 
        //对象引用
        MethodRefObject obj = new MethodRefObject();
          printString(obj::printUpperCase);
        }
    }

    2.通过类名称引用静态方法
    由于在java.lang.Math 类中已经存在了静态方法abs ,所以当我们需要通过Lambda来调用该方法时,有两种写
    法。首先是函数式接口:

    @FunctionalInterface
    public interface Calcable {
        int calc(int num);
    }

    第一种写法是使用Lambda表达式:

    public class Demo05Lambda {
        private static void method(int num, Calcable lambda) {
            System.out.println(lambda.calc(num));
        }
        public static void main(String[] args) {
            method(‐10, n ‐> Math.abs(n));
        }
    }

    但是使用方法引用的更好写法是:

    public class Demo06MethodRef {
      private static void method(int num, Calcable lambda) {
        System.out.println(lambda.calc(num));
      }
      public static void main(String[] args) {
        //Lambda
        int absnum = method(-10, (n) -> {
            return Math.abs(n);
        });
        int absnum2=methodAbs(-9,Math::abs);
        System.out.println(absnum);
        System.out.println(absnum2);
      }
    }

    在这个例子中,下面两种写法是等效的:
    Lambda表达式: n -> Math.abs(n)
    方法引用: Math::abs

    3.通过super引用成员方法
    如果存在继承关系,当Lambda中需要出现super调用时,也可以使用方法引用进行替代。首先是函数式接口:

    @FunctionalInterface
    public interface Greetable {
    void greet();
    }

    然后是父类Human 的内容:

    public class Human {
      public void sayHello() {
        System.out.println("Hello!");
      }
    }

    最后是子类Man 的内容,其中使用了Lambda的写法:

    public class Man extends Human {
    @Override
    public void sayHello() {
      System.out.println("大家好,我是Man!");
    }
    //定义方法method,参数传递Greetable接口
    public void method(Greetable g){
      g.greet();
    }
    public void show(){
      //调用method方法,使用Lambda表达式
      method(()‐>{
      //创建Human对象,调用sayHello方法
      new Human().sayHello();
      });
      //简化Lambda
      method(()‐>new Human().sayHello());
      //使用super关键字代替父类对象
      method(()‐>super.sayHello());
    }
    }

    但是如果使用方法引用来调用父类中的sayHello 方法会更好,例如另一个子类Woman :

    public class Man extends Human {
    @Override
    public void sayHello() {
      System.out.println("大家好,我是Man!");
    }
    //定义方法method,参数传递Greetable接口
    public void method(Greetable g){
      g.greet();
    }
    public void show(){
      method(super::sayHello);
    }
    }

    在这个例子中,下面两种写法是等效的:
    Lambda表达式: () -> super.sayHello()
    方法引用: super::sayHello

    4.通过this引用成员方法
    this代表当前对象,如果需要引用的方法就是当前类中的成员方法,那么可以使用“this::成员方法”的格式来使用方法引用。首先是简单的函数式接口:

    @FunctionalInterface
    public interface Richable {
      void buy();
    }

    下面是一个丈夫Husband 类:

    public class Husband {
    private void marry(Richable lambda) {
      lambda.buy();
    }
    public void beHappy() {
      marry(() ‐> System.out.println("买套房子"));
    }
    }

    开心方法beHappy 调用了结婚方法marry ,后者的参数为函数式接口Richable ,所以需要一个Lambda表达式。
    但是如果这个Lambda表达式的内容已经在本类当中存在了,则可以对Husband 丈夫类进行修改:

    public class Husband {
    private void buyHouse() {
      System.out.println("买套房子");
    }
    private void marry(Richable lambda) {
      lambda.buy();
    }
    public void beHappy() {
      marry(() ‐> this.buyHouse());
    }
    }

    如果希望取消掉Lambda表达式,用方法引用进行替换,则更好的写法为:

    public class Husband {
    private void buyHouse() {
      System.out.println("买套房子");
    }
    private void marry(Richable lambda) {
      lambda.buy();
    }
    
    public void beHappy() {
      //Lambda
      marry(()->{
          this.byHouse();
      });
      //this引用
      marry(this::buyHouse);
     }
    }

    在这个例子中,下面两种写法是等效的:
    Lambda表达式: () -> this.buyHouse()
    方法引用: this::buyHouse

    5.类的构造器引用
    由于构造器的名称与类名完全一样,并不固定。所以构造器引用使用类名称::new 的格式表示。首先是一个简单的Person 类:

    public class Person {
    private String name;
    public Person(String name) {
      this.name = name;
    }
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
    }

    然后是用来创建Person 对象的函数式接口:

    public interface PersonBuilder {
      Person buildPerson(String name);
    }

    要使用这个函数式接口,可以通过Lambda表达式:

    public class Demo09Lambda {
    public static void printName(String name, PersonBuilder builder) {
      System.out.println(builder.buildPerson(name).getName());
    }
    public static void main(String[] args) {
      printName("小花", name ‐> new Person(name));
    }
    }

    但是通过构造器引用,有更好的写法:

    public class Demo10ConstructorRef {
    public static void printName(String name, PersonBuilder builder) {
      System.out.println(builder.buildPerson(name).getName());
    }
    public static void main(String[] args) {
      printName("小美", Person::new);
    }
    }

    在这个例子中,下面两种写法是等效的:
    Lambda表达式: name -> new Person(name)
    方法引用: Person::new

    6.数组的构造器引用
    数组也是Object 的子类对象,所以同样具有构造器,只是语法稍有不同。如果对应到Lambda的使用场景中时,需要一个函数式接口:

    @FunctionalInterface
    public interface ArrayBuilder {
      int[] buildArray(int length);
    }

    在应用该接口的时候,可以通过Lambda表达式:

    public class Demo11ArrayInitRef {
    private static int[] initArray(int length, ArrayBuilder builder) {
      return builder.buildArray(length);
    }
    public static void main(String[] args) {
      int[] array = initArray(10, length ‐> new int[length]);
    }
    }

    但是更好的写法是使用数组的构造器引用:

    public class Demo12ArrayInitRef {
    private static int[] initArray(int length, ArrayBuilder builder) {
      return builder.buildArray(length);
    }
    public static void main(String[] args) {
      int[] array = initArray(10, int[]::new);
    }
    }

    在这个例子中,下面两种写法是等效的:
    Lambda表达式: length -> new int[length]
    方法引用: int[]::new

  • 相关阅读:
    html5标签---不常用新标签的整理
    拖拽demo--兼容--全局捕获
    Linux now!--网络配置
    windows下 memcached 和 redis 服务器安装
    MySQL5.6安装步骤(windows7/8_64位)
    zend 环境
    mysql自增id超大问题查询
    烦人的运营后台导出大批量数据
    kafka环境搭建和使用(python API)
    分布式系统中zookeeper实现配置管理+集群管理
  • 原文地址:https://www.cnblogs.com/itmu89/p/11967981.html
Copyright © 2011-2022 走看看