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?
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? Generic type information is not present at runtime. C. You cannot create an instance using a generic class type parameter.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With