1

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()).

6
  • 4
    It's impossible. Read about type erasure. The best you can do is add another parameter Class<T> clazz to the method. Commented Apr 3, 2016 at 19:37
  • T is Object at compile time in this case, so Object.class does the trick. Otherwise, how about t.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 for T. Commented Apr 3, 2016 at 19:39
  • T is the weak type, however getClass() returns the class of the strong type. See this question Commented Apr 3, 2016 at 19:41
  • @PaulBoddington erasure has nothing to do this this at all. T is Object because there are no bounds, so at compile time T becomes Object. At run time, then t.getClass gets the type of the variable passed in. Commented Apr 3, 2016 at 19:42
  • 1
    @BoristheSpider But if the OP does MyClass.<CharSequence>foo("bar"), he wants to be able to get CharSequence.class at runtime inside the method. This is impossible due to type erasure. Commented Apr 3, 2016 at 19:44

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I am from C++, where we use generics to infer types a lot. Sadly, it is not possible in Java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.