Get request of type of general type in method

I have a method that returns a generic type, is there a way to get the value <T>without having to give it 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?

+3
source share
2 answers

No, you need to explicitly pass type information. Java discards all type information at compile time. This is called type erasure. That is why the toArray method for collection objects requires an array of type T to return an array of type T. It uses this input array exclusively for type information.

+9
source

Java . Class<?> Class , (, newInstance). , . generic .

+2

Source: https://habr.com/ru/post/1751776/


All Articles