Reputation: 819
I want my Java method to return a generic T. I can't get it to work. My method executes a passed in method on a threadpool executor and waits for the result via a Future.get(), I want to pass the result back and this result can be different depending on the method passed in on the Supplier.
This is what I have, it works but I need to cast to the correct type when using. I would prefer using a T t style instead of the Object.
public Object executeThis(Supplier<T> request) throws RejectedExecutionException {
Object obj = null;
try {
Future future = executor.submit(() -> request.get());
obj = future.get(timeoutInMilis, TimeUnit.MILLISECONDS);
} catch (ExecutionException | InterruptedException e) {
}
}
Upvotes: 0
Views: 800
Reputation:
To return a generic type :
public <T> T executeThis(Supplier<T> request){}
You just need to declare generic type before the return type inside diamond operator , then declare the method return type (T)
You have to modify this :
Future future = executor.submit(() -> request.get());
obj = future.get(timeoutInMilis, TimeUnit.MILLISECONDS);
to :
Future<T> future = executor.submit(() -> request.get());
T obj = future.get(timeoutInMilis, TimeUnit.MILLISECONDS);
Upvotes: 2