Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class of T from Vector<T> in java [duplicate]

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?

like image 414
Hasan Mutlu Avatar asked May 18 '13 20:05

Hasan Mutlu


1 Answers

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.

like image 77
confusopoly Avatar answered Nov 14 '22 15:11

confusopoly