Ability to call with different return types

I would like to execute different methods in a separate thread depending on the parameters that are given to the constructor. However, the Callable interface allows only one of the return parameters.

It should work as follows:

Future<String> result = executor.submit(ClassThatImplementsCallable(RETURN_STRING)); Future<Integer> result = executor.submit(ClassThatImplementsCallable(RETURN_INT)); ClassThatImplementsCallable(RETURN_NOTHING); 

To return either null (respectively a reference to Void) or any other type of type String or Integer, I must use T without any restrictions, for example:

 public static class CallableTest<T> implements Callable<T>{ T value; CallableTest(T value) { this.value = value; } public T call(){ return value; } } 

However, this is not what I want to achieve, but it also makes no sense to extend Void and implement some other interface.

+4
source share
2 answers

I would like to execute different methods in a separate thread depending on the parameters that are assigned to the constructor.

So, when you send Callable to ExecutorService , you get the future with the same type:

 Future<String> stringResult = executor.submit(new MyCallable<String>()); Future<Integer> stringResult = executor.submit(new MyCallable<Integer>()); 

What you cannot do is have one Future result that returns one of two different types: String or Integer , based on the arguments when building the ExecutorService . I think this is what you are asking for.

One option is to create a small wrapper class:

 public class StringOrInteger { final String s; final Integer i; public StringOrInteger(String s) { this.s = s; this.i = null; } public StringOrInteger(Integer i) { this.s = null; this.i = i; } public boolean isString() { return this.s != null; } } 

Then your executor will send a Callable<StringOrInteger> , and the StringOrInteger instances returned by Future<StringOrInteger> will either be set to s or i .

An extremely ugly alternative would be to return Object and use instanceof to figure out what type it is. But I won’t even show the code for this implementation, because it will give me hives.

+7
source

You can use the Command pattern with the visitor pattern.

Define a class of commands and wrap your processing logic along with parameters and return types. then pass this command object as a parameter, and also use it as the result type.

Later in the code, you can use the visitor template to deal with two specific commands.

+1
source

Source: https://habr.com/ru/post/1484284/


All Articles