Reputation: 189
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()).
Upvotes: 1
Views: 708
Reputation: 2566
If you want to keep your signature it is not possible. However, there's a way to solve this by providing the type as a separate argument.
static <T> void foo(T t, Class<T> cls) {
// use cls
}
Then instead of invoking
MyClass.<Collection> foo(new ArrayList());
you call
MyClass.foo(new ArrayList(), Collection.class);
Upvotes: 2