zoukankan      html  css  js  c++  java
  • Java 实现函数回调

    在Java里没用委托(delegate)这方法,所以想要实现回调还是有些麻烦。(想了解C#如何实现?请查看:http://www.cnblogs.com/Martin_Q/p/4478494.html)

    那么在Java如何实现回调方式?其实在百度里搜一下一堆这样的教程,我也只是从上面的其中一篇抄下来,修改成自己想要的。

    不过我的使用有点点不一样,在为我是在程序出现异常的时候再去主动调用回调的函数。而且异常部份的代码在一个Jar包里!少废话,下面开始:

    public final class Dump{
        private static final long CB_USER_FUNCTION_MILLIS = 200;
        
        /**
         * 回调函数接口
         * @author Administrator
         */
        public static interface CallBack{
            void UserFunctionCB();
        }
        
        private static CallBack cbFunction;
        
        /**
         * 设置回调函数
         * @param cbFun
         */
        public static void  setCallBackFunction(CallBack cbFun){
            cbFunction = cbFun;
        }
        
        /**
         * 当出现异常时会自动回调此函数,具体如何实现异常回调就不在这里详细描述了
         */
        public static void hanleNDKException(){
            if(cbFunction != null)
            {
                Thread th = new Thread() 
                {
                    @Override
                    public void run() 
                    {
                        cbFunction.UserFunctionCB();
                    }
                };
                th.start();
                
                try 
                {
                    // 允许用户的执行时间,超过时间后将不再管此线程执行结果                
                    th.join(CB_USER_FUNCTION_MILLIS);
                } 
                catch (InterruptedException e) 
                {
                    Logger.logError(LOG_TAG, "Callback user function on thread.join(millis) Error:", e);
                }
            }
            
            // do something
        }
    }

    外面调用的函数如何去实现UserFunctionCB这函数呢?相信大家都知道了。

    public class TestCB{
        public static void main(String[] args){
            
            Dump.setCallBackFunction(new Dump.CallBack() {
                @Override
                public void UserFunctionCB() {
                    // 这里就是你需要实现的函数,回调的时候会执行你的这个函数
                    // 你可以在这里添加任意内容,不过你得保证他能在你的指定时间内完成
                    System.out.println("Hello Call Back Function!");
                }
            });
            
            // 以下是一个异常触发的操作
            String abc = null;
            abc.toString();
        }
    }

    到这里整个回调过程已经完成了,当出现任何异常的时候,都会去执行你的函数,去获取你想需要的一些内容!

  • 相关阅读:
    [Algorithms] Insertion sort algorithm using TypeScript
    [Algorithms] Determine if a string is a palindrome
    [Algorithm] Determine if two strings are an anagram
    [Vue + TS] Watch for Changes in Vue Using the @Watch Decorator with TypeScript
    [Vue +TS] Use Two-Way Binding in Vue Using @Model Decorator with TypeScript
    uvc摄像头代码解析7
    并查集
    流程节点多场景多表单
    【图像识别】 图像处理和图像分析(leptonica)leptonica-1.68安装配置 (vs2008)
    Eclipse完美汉化教程
  • 原文地址:https://www.cnblogs.com/Martin_Q/p/4494670.html
Copyright © 2011-2022 走看看