简体   繁体   中英

How do I create a Java generics object with a Class object as the type parameter?

For example,

// full_class_name is something like "java.lang.String"

Class<?> cls = Class.forName(full_class_name);

Then I want to create a Vector of "cls" objects. Is that possible? Vector certainly doesn't work. I don't want a general Vector<?> object.

I'm a Java newbie. Thanks.

Java Generics are only applicable at compile time, thanks to something called type erasure . That means if you don't know what object you are going to store in a collection at compile time then generics can't help you.

From a coding point of view you can create Vector<Object> to get an unrestricted Vector which won't give compile time warnings.

Incidentally Vector is an old collection and much better replaced by a newer kind like ArrayList.

Vector<Class<?>> v

would be a vector of classes of unknown type;

Vector<Class<String>>

would be a vector of String.class objects; This doc has more on type tokens, which I think is what you need. I don't see how it makes sense to have a collection of just one type of Class object, what are you trying to accomplish?

Generaly, if you don't know the object class before creating a vector, you have no other choice, but raw Vector ( but it gives ide warning ) or Vector. But if you know the class at compile-time, you should use it:

Vector<MyClass>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM