在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);
            }
            
        });
    }
}

  

  

转载于:https://www.cnblogs.com/buyishi/p/8596874.html

你可能感兴趣的:(在Java中如何编写回调函数,以及回调函数的简单应用)