一、通过对象名来引用方法
对象::成员方法
对象和方法已经存在了可以使用
public class MethodreObjedg { public void print_up_string(String s){ System.out.println(s.toUpperCase()); } }
public interface Printable { void pirnt(String s); }
private static void showpitn(Printable pr) { pr.pirnt("hello,world"); }
MethodreObjedg objedg = new MethodreObjedg(); showpitn(objedg::print_up_string);
二、通过类名引用静态成员方法
类名::静态成员方法
@FunctionalInterface public interface Calcable { public abstract int cal_abs(int number); }
public class demo{ public static void main(String[] args) { System.out.println(method(-1, (number) -> Math.abs(number))); System.out.println(method(-2, Math::abs)); } public static int method(int number,Calcable cal){ return cal.cal_abs(number); } }
三、通过super引用父类的成员方法
super::方法名
函数接口
@FunctionalInterface public interface Greetable { public abstract void greet(); }
父类
public class Human { public void say(){ System.out.println("hello,Human"); } }
子类
public class Persion extends Human { @Override public void say() { System.out.println("hello,Persion"); } public void method(Greetable g){ g.greet(); } public void show(){ method(()->{ Human human = new Human(); human.say(); }); method(super::say); } public static void main(String[] args) { Persion persion = new Persion(); persion.show(); } }
四 通过this引用本类的成员方法
this::方法名
@FunctionalInterface public interface Greetable { public abstract void greet(); }
public class green_test { public void method(Greetable greetable) { greetable.greet(); } public void say() { System.out.println("我是本类方法"); } public void show() { method(this::say); } public static void main(String[] args) { new green_test().show(); } }
五 通过类的构造器引用
类名::new
public class Persion { private String name; public Persion() { } public Persion(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
@FunctionalInterface public interface PersionBuilder { public abstract Persion builderpersion(String name); }
public class demo { public static void method(PersionBuilder pb,String name){ Persion per=pb.builderpersion(name); System.out.println(per.getName()); } public static void main(String[] args) { method((name)->new Persion(name),"张无忌"); method(Persion::new,"张三丰"); } }
六 数组的构造器引用
int[]::new
@FunctionalInterface public interface Array_build { public abstract int[] buildarray(int number); }
public class demo_arraybuild { public static int[] createint(Array_build ab,int num){ return ab.buildarray(num); } public static void main(String[] args) { int[] arr1 = createint((number) -> new int[ number], 5); int[] arr2 = createint(int[]::new, 5); System.out.println(Arrays.toString(arr1)); System.out.println(Arrays.toString(arr2)); } }