jdk8新特性之方法引用

目录

 

一、方法引用概念

二、方法引用语法

2.1 引用特定对象的实例方法

2.2通过类名引用静态成员方法

2.3 Super引用父类成员方法

2.4 通过this引用本类成员方法

 


一、方法引用概念

使用双冒号 :: 将实例引用或者类名和方法分开

如果编译只有一行的Lambda表达式来调用方法,不妨考虑调用等价的方法引用

方法引用可以使语言的构造更紧凑简洁,减少冗余代码。

Lambda表达式写法

 Stream.of(1,2,3).forEach(s -> System.out.println(s));

方法引用写法:

Stream.of(1,2,3).forEach(System.out::println);

二、方法引用语法

2.1 引用特定对象的实例方法

object::instanceMethod

引用特定对象的实例方法,如System.out::println

  • 创建一个ToUpperCase类

public class ToUpperCase {
    public void printString(String str) {
        System.out.println(str.toUpperCase());
    }
}

  • 要使用lambda就需要有一个接口Printable

public interface Printable {
    void print(String s);

}

  • 使用方法引用

public class Demo {
    public static void printString(Printable p) {
        p.print("hello");
        
    }
    public static void main(String[] args) {
//      創建ToUpperCase對象
      ToUpperCase obj = new ToUpperCase();
      printString(obj::printString);
    }
    
}

2.2通过类名引用静态成员方法

Class::staticMethod

引用静态方法,如Math::abs

前提:类和静态成员方法已经存在

  • 定义一个接口

public interface Cacable {
    int calAbs(int number);

}

  • 使用方法引用

public class Demo {
    public static int method(int number,Cacable c) {
        return c.calAbs(number);
        
    }
    
    public static void main(String[] args) {
        
        int number = method(-10, Math::abs);
        System.out.println(number);

    }

2.3 Super引用父类成员方法

  • 创建Greetable接口

public interface Greetable {
    void greet();

}

  • 父类

public class Human {
    public void syaHello() {
        System.out.println("hello human");
    }

}
 

  • 子类

public class Man extends Human{
//    重寫sayHello
    @Override
    public void sayHello() {
        System.out.println("hello man");
    }
//    。定義一個方法參數傳遞Greetable接口
    public void method(Greetable g) {
        g.greet();
    }
    
    public void show() {
        method(() -> {
//            創建父類對象
            Human human = new Human();
            human.sayHello();
        });
//        因為游資弗雷,所以存在一個關鍵字super,我們可以直接使用super調用父類的成員方法
        method(() -> {
//          創建父類對象
          super.sayHello();
      });
//        方法引用
        method(super::sayHello);
        
        
    }
    
    public static void main(String[] args) {
        new Man().show();
        
    }

}
 

2.4 通过this引用本类成员方法

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

//    。定義一個方法參數傳遞Greetable接口
    public void method(Greetable g) {
        g.greet();
    }
    
    public void show() {
        method(this::buy);
   
        
    }
    
    public static void main(String[] args) {
        new Man().show();
        
    }

2.5 构造方法的引用

printName(name,Person::new)

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值