先给出一个小demo
package package2;
import java.util.function.Function;
public class Main {
public static void main(String[] args){
System.out.println("main");
Main main = new Main();
main.F(new method1());
System.out.println("==========");
main.F(new method2());
}
public void F(method method){
Function f = Function.identity();
method = (package2.method) f.apply(method);
method.m();
}
}
package package2;
public interface method {
public void m();
}
package package2;
public class method1 implements method{
public method1() {
System.out.println("method1");
}
@Override
public void m(){
System.out.println("m1");
}
}
package package2;
public class method2 implements method{
public method2() {
System.out.println("method2");
}
@Override
public void m(){
System.out.println("m2");
}
}
运行结果:
main
method1
m1
==========
method2
m2
Process finished with exit code 0
个人理解:
有没有发现只要继承同一个接口,在调用的时候指定一下就可以换成其他的方法啦。很方便啊。