方法引用

之前的JDK中,只有数组、类、接口具备引用操作。现在追加了方法引用。引用的本质就是别名,因此,方法引用也就是方法的别名。

  • 引用静态方法:类名称:: static 方法名称
  • 引用某个对象的方法: 实例化对象::普通方法名称
  • 引用某个特定类的方法:类名称::普通方法
  • 引用构造方法:类名称::new

范例: 引用静态方法


public class Demo1 {
    @FunctionalInterface
    interface IUtil<R,P> {
        public R transform(P p);
    }

    public static void main(String args[]){
        IUtil<String,Integer> iu = String::valueOf;
        String str = iu.transform(1000);
        System.out.println(str.length());
    }
}

就相当于给String的valueOf方法起了一个接口中的别名。

范例: 引用某个对象的方法

public class Demo2 {
    @FunctionalInterface
    interface IUtil<R> {
        public R transform();
    }

    public static void main(String args[]){
        IUtil<String> iu = "Hello"::toUpperCase;   //实现方法引用
        String str = iu.transform();
        System.out.println(str);
    }
}

范例: 引用某个特定类的普通方法

public class Demo3 {
    @FunctionalInterface
    interface IUtil<R,P> {
        public R bijiao(P p1, P p2);
    }

    public static void main(String args[]){
        IUtil<Integer,String> iu = String::compareTo;
        Integer whichBig = iu.bijiao("Hello","World");
        System.out.println(whichBig);
    }
}

范例:引用构造方法:类名称::new

class Person {
    private String name;
    private Integer age;

    public Person(String name,Integer age){
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

@FunctionalInterface
interface IUtil<P, S, I>{
    public P create(S s, I i);
}
public class Demo4 {
    public static void main(String args[]){
        IUtil<Person, String, Integer> iu = Person::new;
        System.out.println(iu.create("lihua",15).toString());
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容