java8方法引用

方法引用

方法引用的要求

  1. 参数类型一致 (并不是必须没有参数!)
  2. 返回值类型一致
  3. 对象调用静态方法没有方法引用的改写

方法引用的几种方式

  1. 类名::new
  2. 类名::静态方法名
  3. 引用名(对象名)::实例方法名
  4. 类名::实例方法名

代码示例

public class No05 {
    public static void main(String[] args) {
        //1.类名::new
        F1 f1 = new F1() {
            @Override
            public String test(String a) {
                return new String(a);
            }
        };
        F1 f11 = (str) -> new String(str);
        F1 f12 = String::new;
        
        //2.类名::静态方法名
        F2 f2 = new F2() {
            @Override
            public int test(int a, int b) {
                return Integer.sum(a, b);
            }
        };
        F2 f21 = (a, b) -> Integer.sum(a, b);
        F2 f22 = Integer::sum;
        
        //3.引用名(对象名)::实例方法名
        T1 t1 = new T1();
        F3 f3 = new F3() {
            @Override
            public void test(int a, int b) {
                t1.test(a, b);
            }
        };
        F3 f31 = (a, b) -> t1.test(a, b);
        F3 f32 = t1::test;
        
        //4.类名::实例方法名
        F4 f4 = new F4() {
            @Override
            public void test(String a) {
                a.toUpperCase();
            }
        };
        F4 f41 = (str) -> str.toUpperCase();
        F4 f42 = String::toUpperCase;
    }
}

interface F1 {
    String test(String a);
}

interface F2 {
    int test(int a, int b );
}
interface F3 {
    void test(int a, int b);
}
interface F4 {
    void test(String a);
}

class T1{
    public void test(int a, int b) {
        System.out.println(a+b);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值