views:

53

answers:

2

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?

+8  A: 

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.

Pace
+2  A: 

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.

thecoop