DWB
DWB

Reputation: 1554

Generic method uses type as argument

I have a generic method which I cannot figure out how to compile

private ConditionalCheckRetryHandler<T> T getConditionalCheckRetryHandler() {
    return new ConditionalCheckRetryHandler<T>;
}

Ideally I would like to call <ClassName>getConditionalCheckRetryHandler() and return a class of that type but T doesn't seem to exist. Is there any way to do this sensibly?

Upvotes: 1

Views: 42

Answers (2)

Dmitry Gorkovets
Dmitry Gorkovets

Reputation: 2286

Your code does not compile.

If you have class

class ConditionalCheckRetryHandler<T>{
   //...   
}

then you can use following method

private <T> ConditionalCheckRetryHandler<T>  getConditionalCheckRetryHandler() {
        return new ConditionalCheckRetryHandler<>();
}

Upvotes: 2

Tamas Rev
Tamas Rev

Reputation: 7174

Usually we do it with a runtime type token:

private ConditionalCheckRetryHandler<T> T getConditionalCheckRetryHandler(Class<T> returnType) {
    return new ConditionalCheckRetryHandler<T>();
}

So you can call it like this: getConditionalCheckRetryHandler(DesiredType.class).

Upvotes: 0

Related Questions