I wrote this code:
public static <T> void getList(Vector<T> result){
System.out.println(result.getClass().getName());
}
I want to write the class name of T
, but I can't get it. How can I do this?
As far as I know you can't. Java generics use type erasure, so at runtime a Vector<T>
behaves just like a Vector
without any template arguments.
What you can do instead is query the type of an element of your vector.
Here's a short description of type erasure: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
See also the answers to this question: Java generics - type erasure - when and what happens
In other words:
void someMethod(Vector<T> values) {
T value = values.get(0);
}
is equivalent to:
void someMethod(Vector values) {
T value = (T) values.get(0);
}
at runtime but with some compile time checks for the type you are casting to.
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