一、什么是回调
一般调用分下面几种:
二、回调详解
public class A1 {
public static void main(String[] args) {
A1 a = new A1();
a.run();
}
public void run() {
new B1().process(this);
}
public void callBack() {
System.out.println("A1回调函数callBack");
}
}
public class B1 {
public void process(A1 a){
System.out.println("B1执行函数process");
a.callBack();
}
}
public class A2 implements IA2 {
public static void main(String[] args) {
A2 a = new A2();
a.run();
}
public void run() {
IA2 a2 = new A2();
new B2().process(a2);
}
public void callBack() {
System.out.println("A2回调函数callBack");
}
}
public interface IA2 {
void callBack();
}
public class B2 {
public void process(IA2 a){
System.out.println("B2执行函数process");
a.callBack();
}
}
public void run() {
new B2().process(()->{
System.out.println("A2 Lambda表达式 回调函数callBack");
});
}
public class A3{
public static void main(String[] args) {
A3 a = new A3();
a.run();
}
public void run() {
B3 b3 = new B3();
try {
b3.process(A3.class,A3.class.getMethod("callBack"));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public void callBack() {
System.out.println("A3回调函数callBack");
}
}
public class B3 {
public void process(Class clazz, Method method){
System.out.println("B3执行函数process");
try {
method.invoke(clazz.newInstance());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}