Java: Method Reference

 

  1. 类名::引用实例方法
    Java 类名只能引用静态方法, 类名引用实例方法是 拿第一个参数作为方法的调用者
    import java.util.function.BiFunction;
    import java.util.function.Function;
    
    public class addThen{
      public static void main(String[] args){
        Function<String, Integer> f1 = s -> s.length();
        System.out.println("f1.apply(\"etymology\") = " + f1.apply("etymology"));
    
        Function<String, Integer> f2 = String::length;
        System.out.println("f2.apply(\"etymology\") = " + f2.apply("etymology"));
    
        BiFunction<String, Integer, String> biFunction = String::substring;
        System.out.println("biFunction.apply(\"etymology\",3) = " + biFunction.apply("etymology", 3));
      }
    }

     

  2. 类名::new
    import java.util.function.BiFunction;
    import java.util.function.Supplier;
    
    public class addThen{
      public static void main(String[] args){
        Supplier<Jot> supplier1 = Jot::new;
        System.out.println("supplier1 = " + supplier1.get());
    
        BiFunction<String,Integer,Jot> supplier2=Jot::new;
        System.out.println("\033[37;7m" + supplier2.apply("jot", 55) + "\033[0m");
    
      }
    }
    
    class Jot{
      String name;
      int age;
    
      @Override
      public String toString(){
        final StringBuilder sb = new StringBuilder("Jot{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
      }
    
      public Jot(){
      }
    
      public Jot(String name, int age){
        this.name = name;
        this.age = age;
      }
    }

     

  3. 数组::new        String[]::new
    public class addThen{
      public static void main(String[] args){
        Function<Integer,String[]> f1=len->new String[len];
        String[] strings = f1.apply(5);
        System.out.println("strings = " + Arrays.toString(strings));
    
        Function<Integer,String[]>  f2=String[]::new;
        String[] strings1 = f2.apply(3);
        System.out.println("strings1 = " + Arrays.toString(strings1));
      }
    }

     

posted @ 2022-05-25 13:04  ascertain  阅读(65)  评论(0编辑  收藏  举报