Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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?

like image 990
CodeMangler Avatar asked Aug 30 '09 13:08

CodeMangler


People also ask

How do you provide the Parametrized type for a generic?

In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.

Is generic type information present at runtime?

Is generic type information present at runtime? Generic type information is not present at runtime. C. You cannot create an instance using a generic class type parameter.

What is generic type class?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.


1 Answers

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.

like image 121
sepp2k Avatar answered Sep 28 '22 15:09

sepp2k