Java 8 新特性:方法引用“::”

Java 8 新特性:方法引用“::”

从对象引用理解方法引用

对象引用相信大家都理解了,就是一个类及对应父类声明的一个指向一个对象的“标记符号”,同样我们也可以这么理解方法引用,它是指向另一个方法的“标记符号”,JDK1.8为此专门定义了一个java.util.function包,作为方法引用的目标类型,用于接收方法引用。这其实就是函数式接口(函数式方法),所以你在定义方法引用之前,一定要先定义一个函数式接口。
一般情况下,方法引用和方法(要指向的那个方法)除了有同样的方法签名之外(什么是方法签名呢?就是方法的返回值和参数列表,因为这个像一个人的签名一样,可以区分方法),函数式接口还要有调用该方法的对象参数,举个大栗子吧.

一般情况指的是未绑定的方法引用。

未绑定的方法引用是指没有关联对象的普通(非静态)方法。 使用未绑定的引用时,我们必须先提供对象:

// 没有方法引用的对象

class X {
  String f() { return "X::f()"; }
}

interface MakeString {
  String make();
}

interface TransformX {
  String transform(X x);
}
//无法用MakeString接受
public class UnboundMethodReference {
  public static void main(String[] args) {
    // MakeString ms = X::f; // [1]
    TransformX sp = X::f;
    X x = new X();
    System.out.println(sp.transform(x)); // [2]
    System.out.println(x.f()); // 同等效果
  }
}

//改良之后

class This {
  void two(int i, double d) {}
  void three(int i, double d, String s) {}
  void four(int i, double d, String s, char c) {}
}

interface TwoArgs {
  void call2(This athis, int i, double d);
}

interface ThreeArgs {
  void call3(This athis, int i, double d, String s);
}

interface FourArgs {
  void call4(
    This athis, int i, double d, String s, char c);
}

public class MultiUnbound {
  public static void main(String[] args) {
    TwoArgs twoargs = This::two;
    ThreeArgs threeargs = This::three;
    FourArgs fourargs = This::four;
    This athis = new This();
    twoargs.call2(athis, 11, 3.14);
    threeargs.call3(athis, 11, 3.14, "Three");
    fourargs.call4(athis, 11, 3.14, "Four", 'Z');
  }
}

但是这里为什么不用呢?这不也是在一个对象里吗,这里我也有疑惑,我说一下我的理解,有不同意见的网友,可以评论,我非常愿意与你们交流

这里call指向了show进行调用,其实调用的是System.out.println方法,而out早在编译期就已经实例化了(因为在System中对out的声明使用了final),所以这是一个绑定的方法引用。

interface Callable{
    void call(String s);
}
class Describe{
    void show(String msg){
        System.out.println(msg);
    }
}

public static void main(String[] args){
    Describe d = new Describe();
    Callable c=d::show;   
    c.call("你好");
}

其实我也有很多不懂的地方,写这篇文章,希望可以抛砖引玉。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值