暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Java新特性解读JDK8之方法和构造函数引用

227decision 2020-01-20
839

方法引用也是一种函数式接口,操作符号是双冒号 ::

方法和构造函数引用的使用,代码如下:

    package com.example.functionalinterfacedemo;


    import java.util.function.BiFunction;
    import java.util.function.Function;
    import java.util.function.Supplier;


    public class MethodRefDemo {

    public static void main(String[] args) {
    //静态方法引用
    Function<String, Long> function=Long::parseLong;
    Long apply = function.apply("123");
    System.out.println(apply);

    //实例方法引用
    String str=new String("实例方法引用");
    Function<String, Integer> function2=String::length;
    Integer len = function2.apply(str);
    System.out.println(len);

    //构造函数:无参
    Supplier<Person> supplier=Person::new;
    Person person = supplier.get();
    System.out.println(person);

    //构造函数引用:一个参数
    Function<String, Person> function3=Person::new;
    Person apply2 = function3.apply("jack");
    System.out.println(apply2);

    //构造函数引用:两个参数
    BiFunction<Integer, String,Person> biFunction=Person::new;
    Person apply3 = biFunction.apply(12, "tony");
    System.out.println(apply3);

    //方法引用作为参数
    test("方法引用作为参数", String::length);

    }
    /**
    * 方法引用作为参数
    * @param param 参数
    * @param function 方法引用
    */
    public static void test(String param,Function<String, Integer> function){
    Integer apply = function.apply(param);
        System.out.println(apply);
      }
    }


    package com.example.functionalinterfacedemo;


    public class Person {
    private Integer age;
    private String name;

    public Person() {
    super();
    }
    public Person(Integer age) {
    super();
    this.age = age;
    }

    public Person(String name) {
    super();
    this.name = name;
    }
    public Person(Integer age, String name) {
    super();
    this.age = age;
    this.name = name;
    }
    public Integer getAge() {
    return age;
    }
    public void setAge(Integer age) {
    this.age = age;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }

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


    最后修改时间:2020-07-01 13:35:50
    文章转载自227decision,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

    评论