Java回调函数详解
什么是回調(diào)函數(shù)(CallBack)
在編寫(xiě)程序時(shí),有時(shí)候會(huì)調(diào)用許多API中實(shí)現(xiàn)實(shí)現(xiàn)的函數(shù),但某些方法需要我們傳入一個(gè)方法,以便在需要的時(shí)候調(diào)用我們傳入進(jìn)去的函數(shù)。這個(gè)被傳入的函數(shù)稱為回調(diào)函數(shù)(Callback function)。
打個(gè)比方,有一個(gè)餐館,提供炒菜的服務(wù),但是會(huì)讓我們選擇做菜的方式,我們?nèi)ミ@家餐館里面吃飯,想吃小龍蝦,我們告訴他想吃小龍蝦后,他詢問(wèn)我們要以何種方式去進(jìn)行烹飪,是煎炒烹炸還是避風(fēng)塘。
在上面的例子中,炒菜是我們需要調(diào)用的方法,也是API庫(kù)中所提供的,而炒菜的方式,則是我們?nèi)ミx擇的,可以我們自己去定義的。
這個(gè)這個(gè)就可以回調(diào)函數(shù),有庫(kù)函數(shù)(Librart function)來(lái)執(zhí)行我們傳入的回調(diào)函數(shù)(Callback function)
在Java中實(shí)現(xiàn)回調(diào)函數(shù)
Callable接口
Interface Callable< V >
在Java1.8官方文檔中給出的內(nèi)容為
代碼示例
import java.util.Random; import java.util.concurrent.Callable;public class CallableExample implements Callable {@Overridepublic Object call() throws Exception {Random generator = new Random();Integer randomNumber = generator.nextInt(5);Thread.sleep(randomNumber * 1000);return randomNumber;} }@Testpublic void callabledTest(){ExecutorService executorService = Executors.newCachedThreadPool();CallableExample callableExample = new CallableExample();Future<Object> future = executorService.submit(callableExample);executorService.shutdown();try{System.out.println(future.get());}catch (Exception e){e.printStackTrace();}}返回值3Callback接口
已知實(shí)現(xiàn)此接口的類
AuthorizeCallback, ChoiceCallback, ConfirmationCallback, LanguageCallback, NameCallback, PasswordCallback, RealmCallback, RealmChoiceCallback, TextInputCallback, TextOutputCallback
這個(gè)接口的實(shí)現(xiàn)了會(huì)被傳遞給CallbackHandler,允許有能力的底層服務(wù)去回應(yīng)這個(gè)回調(diào)方法,已便進(jìn)行諸如數(shù)據(jù)檢索等信息。回調(diào)函數(shù)不檢索或顯示底層安全服務(wù)請(qǐng)求的信息。回調(diào)實(shí)現(xiàn)只是提供了將這些請(qǐng)求傳遞給應(yīng)用程序的方法,并且對(duì)于應(yīng)用程序,如果合適的話,可以將請(qǐng)求的信息返回給底層的安全服務(wù)。
這個(gè)接口是可以自己定義的,定制適用于當(dāng)前業(yè)務(wù)的callback接口類型來(lái)表示不同類型的回調(diào)函數(shù)
callback接口的源碼
public interface Callback { }## CallbackHandler接口 方法:handle(Callback [] callbacks) 這個(gè)方法是用來(lái)處理處理callback類型的 官方實(shí)例: ```javapublic void handle(Callback[] callbacks)throws IOException, UnsupportedCallbackException {for (int i = 0; i < callbacks.length; i++) {if (callbacks[i] instanceof TextOutputCallback) {// display the message according to the specified typeTextOutputCallback toc = (TextOutputCallback)callbacks[i];switch (toc.getMessageType()) {case TextOutputCallback.INFORMATION:System.out.println(toc.getMessage());break;case TextOutputCallback.ERROR:System.out.println("ERROR: " + toc.getMessage());break;case TextOutputCallback.WARNING:System.out.println("WARNING: " + toc.getMessage());break;default:throw new IOException("Unsupported message type: " +toc.getMessageType());}} else if (callbacks[i] instanceof NameCallback) {// prompt the user for a usernameNameCallback nc = (NameCallback)callbacks[i];// ignore the provided defaultNameSystem.err.print(nc.getPrompt());System.err.flush();nc.setName((new BufferedReader(new InputStreamReader(System.in))).readLine());} else if (callbacks[i] instanceof PasswordCallback) {// prompt the user for sensitive informationPasswordCallback pc = (PasswordCallback)callbacks[i];System.err.print(pc.getPrompt());System.err.flush();pc.setPassword(readPassword(System.in));} else {throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");}}}// Reads user password from given input stream.private char[] readPassword(InputStream in) throws IOException {// insert code to read a user password from the input stream}通過(guò)傳入不同的已經(jīng)實(shí)現(xiàn)了Callback接口的實(shí)現(xiàn)類,通過(guò)分析不同實(shí)現(xiàn)類的類型來(lái)進(jìn)行不同的處理,調(diào)用形參實(shí)現(xiàn)類內(nèi)的方法(回調(diào))。
一般來(lái)說(shuō)如何使用
在一般工作中,我們都是自己定義接口,寫(xiě)實(shí)現(xiàn)類,來(lái)進(jìn)行回調(diào)的
自定義的回調(diào)函數(shù)實(shí)例:
這個(gè)是Callback接口類,我們一會(huì)兒要是用它來(lái)創(chuàng)造內(nèi)部匿名類,來(lái)實(shí)現(xiàn)這個(gè)接口,完成字表的篩選工作
import java.util.List;public interface CallBackInterface {Object process(List<String> list); }這個(gè)是處理端,通過(guò)handler方法,調(diào)用傳入的CallBackInterface類型中的方法,來(lái)對(duì)字表進(jìn)行操作
import lombok.Data;import java.util.ArrayList; import java.util.List; @Data public class WorldListHandler {List<String> stringList = new ArrayList<>();public void execute(CallBackInterface callBackInterface){Object process = callBackInterface.process(stringList);System.out.println(process);}}使用CallBackInterface接口并實(shí)現(xiàn)它,來(lái)讓Handler來(lái)調(diào)用它其中的process方法來(lái)完成對(duì)字表的篩選
@Testpublic void callableTest2(){List<String> list = Arrays.asList("123","asd","1432","fsd","543","987","tre");WorldListHandler worldListHandler = new WorldListHandler();worldListHandler.setStringList(list);worldListHandler.execute(new CallBackInterface() {@Overridepublic Object process(List<String> list) {List<String> collect = list.stream().filter(e -> e.contains("1")).collect(Collectors.toList());worldListHandler.setStringList(collect);return true;}});worldListHandler.getStringList().forEach(e-> System.out.println(e));}結(jié)果:true為process的返回值,剩下的為我們篩選出字表中包含有1的字符串。
true
123
1432
總結(jié)
以上是生活随笔為你收集整理的Java回调函数详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ASP.NET中下载文件的几种方法
- 下一篇: java中直角三角形第三条边,Java编