56-lambda--方法引用

47 阅读1分钟
### ​方法引用只能"引用"已经存在的方法  方法引用是对lambda表达式的一种简化书写格式
/*
    方法引用格式符:    ::
    输出语句: System.out.println(...);
    方法引用: System.out::println      
    限制:
        1.lambda表达式{}中只能有一句话
        2.lambda表达式中不能对参数进行任何处理
        
 */ 
/接口
@FunctionalInterface
public interface MyPrinter {  
public class Demo04MethodRef {
    public static void main(String[] args) { 
        show(str,System.out::println);
     对象名的方法引用:   对象名::方法名称     show(money,as::buyComputer);
      public static void buyComputer(Integer money) {
        System.out.println("很高兴为您买到价值为: "+money+" 元的一台电脑");
    }   
     静态方法的方法引用: 类名称::方法名称  printRanNum(Math::random);
    } 
     
} 
    类名引用构造方法 类名::new  show(name,Person::new);//把name交给Person类的构造方法 
    public class Person {
    private String name;
	//toString方法,空参/满参构造,get/set方法
}
  数组--构造引用   int[] array = createArray(int[]::new, 3);
        show(len,int[]::new);
  public static int[] createArray(Function<Integer , int[]> fun , int n){
        int[] p = fun.apply(n);
        return p
  }   
    public static void show(Integer num,Function<Integer, int[]> fun) {
        int[] arr = fun.apply(num);
        System.out.println("数组长度: "+arr.length);
    }