Is there an interface similar to Callable but with arguments?

后端 未结 8 1586
小蘑菇
小蘑菇 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:06

    I've had the same requirement recently. As others have explained many libs do provide 'functional' methods, but these do not throw exceptions.

    An example of how some projects have provided a solution is the RxJava library where they use interfaces such as ActionX where 'X' is 0 ... N, the number of arguments to the call method. They even have a varargs interface, ActionN.

    My current approach is to use a simple generic interface:

    public interface Invoke  {     
        public T call(V data) throws Exception;     
    //  public T call(V... data) throws Exception;    
    }
    

    The second method is preferable in my case but it exhibits that dreaded "Type safety: Potential heap pollution via varargs parameter data" in my IDE, and that is a whole other issue.

    Another approach I am looking at is to use existing interfaces such as java.util.concurrent.Callable that do not throw Exception, and in my implementation wrap exceptions in unchecked exceptions.

提交回复
热议问题