Java 回调函数callback 用法
1.定义回调函数接口
里面包含一个方法
public interface CallBack {
public void execute();
}
2.定义回调函数的实现
public class BookCallBack implements CallBack{
private String bookName;
private String author;
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public void execute() {
this.bookName = "The little prince";
this.author = "Antoine";
System.out.println("---------callback实现类 bookName=="+ this.bookName +" author==="+this.author);
}
}
3.定义业务处理类
业务处理类里的方法形参传入CallBack接口。
业务处理类里的方法内容包括:处理业务和执行回调函数。
//业务处理类
public class TestBookCallBack {
public void test(CallBack callBack){
//1.处理业务
System.out.println("---------业务处理类 TestBookCallBack---------");
//2.执行回调函数
callBack.execute();
}
}
4.1 定义主函数-使用匿名内部类 实现callback
import org.junit.Test;
public class Main {
@Test
public void main() {
TestBookCallBack testBookCallBack = new TestBookCallBack();
testBookCallBack.test(new CallBack() {
@Override
public void execute() {
System.out.println("-------------------Anonymous Inner Class-------------------");
}
});
}
}
执行结果为
---------业务处理类 TestBookCallBack---------
---------Anonymous Inner Class---------
4.2定义主函数,使用callback的实现类 实现callback
import org.junit.Test;
public class Main {
@Test
public void main() {
TestBookCallBack testBookCallBack = new TestBookCallBack();
BookCallBack bookCallBack = new BookCallBack();
testBookCallBack.test(bookCallBack);
System.out.println("---------main---------在主函数中 获取callback实现类里定义的变量值----------" + bookCallBack.getBookName()+"----"+ bookCallBack.getAuthor());
}
}
执行结果
---------业务处理类 TestBookCallBack---------
---------callback实现类 bookName==The little prince author===Antoine
---------main---------在主函数中 获取callback实现类里定义的变量值----------The little prince----Antoine