Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
Thizzer Avatar asked Jul 04 '26 07:07

Thizzer


1 Answers

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.

like image 134
Pace Avatar answered Jul 06 '26 05:07

Pace