Thizzer
Thizzer

Reputation: 16663

Get request generic type in method

I have a method which returns a generic type, is there a way to retrieve the value of <T> without having to give this by parameters?

public <T> T getObject(String location, String method)
{
    // ! Here I want to retrieve the class of T
    Class<?> requestedClass = getMeTheClassThatWasRequested();

    return requestedClass;
}

Is there any way to do this?

Upvotes: 3

Views: 606

Answers (2)

thecoop
thecoop

Reputation: 46098

Java generics are only available at compile time. A Class<?> reference will be compiled into a Class with casts inserted in the appropriate place (for instance, the return value of the newInstance method). So no, you can't. You have to pass it into the method as a generic type variable when you use it.

Upvotes: 2

Pace
Pace

Reputation: 43817

Nope, you have to explicitly pass in the type information. Java discards all type information at compile time. This is called 'type erasure'. This is also why the toArray method on collections objects requires an array of type T in order to return an array of type T. It uses that input array solely for type information.

Upvotes: 9

Related Questions