在Java中如何編寫回調函數,以及回調函數的簡單應用


import static java.lang.System.out;
import static java.lang.System.err;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CallbackExample1 {
    private interface Responser {
        void onSuccess(String data);
        void onFailed(String prompt);
    }
    private static String doSomething() {
        try {
            out.println("開始操作...");
            Thread.sleep(5000); //模擬耗時操作(如網絡請求),操作正常返回"Success","Success"表示有效的數據
            return "Success";
        } catch (InterruptedException ex) {
            Logger.getLogger(CallbackExample1.class.getName()).log(Level.SEVERE, null, ex);
            //操作出現問題返回"Failed","Failed"包含錯誤提示,如錯誤碼等
            return "Failed";
        }
    }
    //使用回調函數完成操作
    private static void callbackDoSomething(Responser responser) {
        try {
            out.println("開始操作...");
            Thread.sleep(5000);
            responser.onSuccess("Success");
        } catch (InterruptedException ex) {
            Logger.getLogger(CallbackExample1.class.getName()).log(Level.SEVERE, null, ex);
            responser.onFailed("Failed");
        }
    }
    public static void main(String[] args) {
        out.println("正常模式 ------ " + doSomething());
        callbackDoSomething(new Responser() {
            @Override
            public void onSuccess(String data) {
                out.println("回調模式 ------ " + data);
            }

            @Override
            public void onFailed(String prompt) {
                err.println("錯誤提示:" + prompt);
            }
            
        });
    }
}

import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.System.err;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CallbackExample2 {
    private interface HttpResponser {
        void onSuccess(String response);
        void onError(String msg);
    }
    private static String httpRequest() {
        try {
            String urlStr = "http://api.eyekey.com/face/Check/checking?app_id=f89ae61fd63d4a63842277e9144a6bd2&app_key=af1cd33549c54b27ae24aeb041865da2&url=http://f.hiphotos.baidu.com/baike/pic/item/562c11dfa9ec8a1366377e5efe03918fa0ecc05a.jpg";
            URLConnection c = new URL(urlStr).openConnection();
            BufferedReader inputFromServer = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String line;
            StringBuilder strBuf = new StringBuilder();
            while ((line = inputFromServer.readLine()) != null) {
                strBuf.append(line);
            }
            return strBuf.toString();
        } catch (IOException ex) {
            Logger.getLogger(CallbackExample2.class.getName()).log(Level.SEVERE, null, ex);
            return ex.toString();
        }
    }
    private static void callbackHttpRequest(HttpResponser httpResponser) {
        try {
            String urlStr = "http://api.eyekey.com/face/Check/checking?app_id=f89ae61fd63d4a63842277e9144a6bd2&app_key=af1cd33549c54b27ae24aeb041865da2&url=http://f.hiphotos.baidu.com/baike/pic/item/562c11dfa9ec8a1366377e5efe03918fa0ecc05a.jpg";
            URLConnection c = new URL(urlStr).openConnection();
            BufferedReader inputFromServer = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String line;
            StringBuilder strBuf = new StringBuilder();
            while ((line = inputFromServer.readLine()) != null) {
                strBuf.append(line);
            }
            httpResponser.onSuccess(strBuf.toString());
        } catch (IOException ex) {
            Logger.getLogger(CallbackExample2.class.getName()).log(Level.SEVERE, null, ex);
            httpResponser.onError(ex.toString());
        }
    }
    public static void main(String[] args) {
        out.println(httpRequest());
        callbackHttpRequest(new HttpResponser() {
            @Override
            public void onSuccess(String response) {
                err.println(response);
            }

            @Override
            public void onError(String msg) {
                err.println(msg);
            }
            
        });
    }
}

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM