在我們的開發過程中,Java回調是我們經常使用到的,比如我們的Thread的內部封裝,還有我們的網絡異步請求回調等等功能都有使用到我們的Java回調,本文主要記錄一下Java回調的開發過程。
- Demo目錄結構爲:
IWeatherUtils 定義接口 Main 運行演示 Weather 實體類 WeatherUtils 實現接口工具類 - 代碼展示:
- IWeatherUtils:
package com.clover.InterfaceCallBack; public interface IWeatherUtils { void getWeather(String city, CallBack callBack); interface CallBack { void success(Weather weather); void error(String msg); } }
-
Main:
package com.clover.InterfaceCallBack; public class Main { public static void main(String[] args) { WeatherUtils weatherUtils = new WeatherUtils(); weatherUtils.getWeather("北京", new IWeatherUtils.CallBack() { @Override public void success(Weather weather) { System.out.println(weather.getMsg()); } @Override public void error(String msg) { System.out.println(msg); } }); } }
-
Weather:
package com.clover.InterfaceCallBack; public class Weather { //城市 private String city; //天氣信息 private String msg; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
- WeatherUtils:
package com.clover.InterfaceCallBack; public class WeatherUtils implements IWeatherUtils { @Override public void getWeather(String city, CallBack callBack) { Weather weather = new Weather(); weather.setCity(city); switch (city) { case "北京": { String msg = city + "今天霧霾嚴重,空氣質量差,建議在家刷劇玩遊戲!"; weather.setMsg(msg); callBack.success(weather); break; } case "廣州": { String msg = city + "今天晴朗,空氣質量優,適合出行!"; weather.setMsg(msg); callBack.success(weather); break; } case "上海": { String msg = city + "今天有大暴雨,建議出門帶傘!"; weather.setMsg(msg); callBack.success(weather); break; } case "深圳": { String msg = city + "今天高溫,建議在家吹空調!"; weather.setMsg(msg); callBack.success(weather); break; } default: { callBack.error(city + "天氣獲取失敗!"); } } } }