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>
精彩评论