1

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Vector is not an old collection, it is synchronized version of ArrayList.
@Vladimir: It isn't explicitly deprecated, but it is old. Vector predates the Java Collections API, as do Stack, Hashtable, Dictionary and Enumeration. It was "retrofitted" to implement the List interface, but most Java programmers would rather use ArrayList than Vector. If you need a synchronized ArrayList you can use Collections.synchronizedList on an ArrayList (or consider whether one of the java.util.concurrent classes would be more appropriate). Vector pretty much only exists for backwards compatibility.
Thanks. I'm trying to parse xml tags such as <library_geometries> or <library_materials>. I want to dynamically create a HashMap of "geometry" objs or "material" objs when I see these tags. Guess I'll have to use a common base class as the type parameter then.
0
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?

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.