Passing function as a parameter in java

后端 未结 6 991
南笙
南笙 2020-11-28 22:13

I\'m getting familiar with Android framework and Java and wanted to create a general \"NetworkHelper\" class which would handle most of the networking code enabling me to ju

6条回答
  •  庸人自扰
    2020-11-28 22:41

    NO interface, NO lib, NO Java 8 needed!

    Just using Callable from java.util.concurrent

    public static void superMethod(String simpleParam, Callable methodParam) {
    
        //your logic code [...]
    
        //call methodParam
        try {
            methodParam.call();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    How to use it:

     superMethod("Hello world", new Callable() {
                    public Void call() {
                        myParamMethod();
                        return null;
                    }
                }
        );
    

    Where myParamMethod() is our passed method as parameter (in this case methodParam).

提交回复
热议问题