FinnTheHuman FinnTheHuman - 2 months ago 6
Java Question

How do I get a Class object from a method's type parameter?

I have a type-parameterized method but I can't call

getClass
on the type-parameterized parameter because it can be
null
, so the only solution I see is to get the
Class
from the type parameter itself, somehow:

public <T> Class myMethod(T obj)
{
//can't do this: return obj.getClass() because null is permitted.
}


This method simply illustrates the problem. My actual method doesn't even return the parameter's class, but uses it in a different way. The core of the problem is this: Is there a way to get the
Class
object that represents the parameterized type of my method's parameter, without using
obj.getClass()
(because in case obj is
null
, I still need to know with what type parameter was the method invoked, for example:
<String>myMethod(null)
must return the
java.lang.String
class object).

EDIT This is not a duplicate of the said question because my class is not parameterized, only my method.

Answer

The core of the problem is this: Is there a way to get the Class object that represents the parameterized type of my method's parameter [...]

No. Class does not contain any information about the type parameter values. Class only contains data about the definition of the class, but not about a use of a type. In fact you cannot get this kind of information about a type parameter because of type erasure (see https://docs.oracle.com/javase/tutorial/java/generics/genMethods.html (methods) and https://docs.oracle.com/javase/tutorial/java/generics/genTypes.html (types)).

Comments