Java回調機制如何理解?

首先,參考一下衆多文章中,把接口回調講得比較淺顯易懂的兩篇文章:ide

淺談Java回調機制 2016-04-09 wa_lid 阿里百川this

Java帝國之撥雲見日識回調 原創 2017-01-05 王欽譽 碼農翻身code

舉個例子接口

網友提供的一些例子,雖然接地氣,可是,不夠專業,仍是欣叔的例子好一些,把代碼取出來,原理講解移步<碼農翻身>公衆號。get

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);
}
相關文章
相關標籤/搜索