首先,参考一下众多文章中,把接口回调讲得比较浅显易懂的两篇文章:
浅谈Java回调机制 2016-04-09 wa_lid 阿里百川
Java帝国之拨云见日识回调 原创 2017-01-05 王钦誉 码农翻身
举个例子
网友提供的一些例子,虽然接地气,但是,不够专业,还是欣叔的例子好一些,把代码取出来,原理讲解移步<码农翻身>公众号。
public class XiaoZhang implements IFileIoCallback {
public void saveStr(){
String fileName = "callback.txt";
String str = "this is a callback demo.";
FileIO fileIO = new FileIO();
fileIO.saveStrToFile(fileName,str,this);
}
@Override
public void onResult(boolean isSave) {
System.out.println(isSave ? "success" : "fail" );
}
}
public class FileIO {
public void saveStrToFile(String fileName, String content, final IFileIoCallback callback){
new Thread(new Runnable() {
@Override
public void run() {
try {
//write str to file...
callback.onResult(true);
}catch (Exception e){
e.printStackTrace();
callback.onResult(false);
}
}
}).start();
}
}
public interface IFileIoCallback {
void onResult(boolean isSave);
}