CodeMangler
CodeMangler

Reputation: 1709

Is there a way to find the type of a template (generic) parameter in Java?

I'm trying to do something like this in Java:

public static <T> T foo() {
  return (T) bar(T);
}

public static Object bar(Class<?> klaz) {
  return klaz.newInstance();
}

But the code doesn't compile since I can't substitute T for a Class<?>.
With a concrete class, I can call bar like:

bar(ConcreteClass.class);

But the same does not work for T. i.e. there's no such thing as T.class

In C#, typeof works for both concrete and template types. So, the call to bar would've been:

bar(typeof(T));

But I haven't been able to find anything similar in Java.

Am I missing something, or does Java not have a way of getting the type of a template parameter? And if Java doesn't have the facility, are there any workarounds?

Upvotes: 11

Views: 4241

Answers (1)

sepp2k
sepp2k

Reputation: 370132

There's no way to get the type. Java's generics use type erasure so even java itself does not know what T is at runtime.

As for workarounds: you could define foo to take a parameter of type Class<T> and then use that.

Upvotes: 15

Related Questions