简体   繁体   中英

return generic type from java method

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) {
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM