Is there an interface similar to Callable but with arguments?

后端 未结 8 1581
小蘑菇
小蘑菇 2021-01-31 02:03

Is there an interface in Java similar to the Callable interface, that can accept an argument to its call method?

Like so:

public interface M         


        
8条回答
  •  执笔经年
    2021-01-31 02:30

    at first it thought that this is done with an interface but then i found that it should be done using an abstract class.

    i have solved it this way:


    edit: lately i just use this:

        public static abstract class callback1{
             public abstract  void run(T value);
        }
    
        public static abstract class callback2{
             public abstract  void run(T value,J value2);
        }
    
        public static abstract class callback3{
             public abstract  void run(T value,J value2,Z value3);
        }
    
    
        public static abstract class callbackret1{
             public abstract  R run(T value);
        }
    
        public static abstract class callbackret2{
             public abstract  R run(T value,J value2);
        }
    
        public static abstract class callbackret3{
             public abstract  R run(T value,J value2,Z value3);
        }
    

    CallBack.java

    public abstract class CallBack {
        public abstract TRet call(TArg val);
    }
    

    define method:

    class Sample2 
    {
        CallBack cb;
        void callcb(CallBack CB)
        {
         cb=CB; //save the callback
         cb.call("yes!"); // call the callback
        }
    }
    

    use method:

    sample2.callcb(new CallBack(){
            @Override
            public Void call(String val) {
                // TODO Auto-generated method stub
                return null;
            }
        });
    

    two arguments sample: CallBack2.java

    public abstract class CallBack2 {
        public abstract TRet call(TArg1 val1,TArg2 val2);
    }
    

    notice that when you use Void return type you have to use return null; so here is a variation to fix that because usually callbacks do not return any value.

    void as return type: SimpleCallBack.java

    public abstract class SimpleCallBack {
        public abstract void call(TArg val);
    }
    

    void as return type 2 args: SimpleCallBack2.java

    public abstract class SimpleCallBack {
        public abstract void call(TArg1 val1,TArg2 val2);
    }
    

    interface is not useful for this.

    interfaces allow multiple types match same type. by having a shared predefined set of functions.

    abstract classes allow empty functions inside them to be completed later. at extending or instantiation.

提交回复
热议问题