I have a generic method, how could I get the class of T?
class MyClass
{
static <T> void foo(T t)
{
// how to get T.class
}
}
t.getClass() gets the most derived class, but T could be a super class so it does not work in case of MyClass.<Collection>foo(new ArrayList()).
Class<T> clazzto the method.TisObjectat compile time in this case, soObject.classdoes the trick. Otherwise, how aboutt.getClass()? P.S. don't let anyone tell you this has anything to do with erasure, it doesn't; you haven't defined any bounds forT.Tis the weak type, howevergetClass()returns the class of the strong type. See this questionTisObjectbecause there are no bounds, so at compile timeTbecomesObject. At run time, thent.getClassgets the type of the variable passed in.MyClass.<CharSequence>foo("bar"), he wants to be able to getCharSequence.classat runtime inside the method. This is impossible due to type erasure.