I'm trying to do something like this in Java:
public static 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?
解决方案
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 and then use that.