简体   繁体   中英

Java Vector of Class objects

I want to create a vector of custom class objects dynamically. When the program is running the tableClassName Variable contains the class name that is rerieved from a xml request. It's giving me a error when i tried the below way.

 Class tableClass = Class.forName(tableClassName).asSubclass(comm.Table.class);
 Vector<tableClass> MappingLookupResu = new Vector<tableClass>();

That's like writing mappingLookupResult = new Vector< String.class >();

mappingLookupResult = new Vector< String >(); is legal, but you're providing an object (of the "Class" class), not a class definition. If your object is a "comm.Table", then try:

mappingLookupResult = new Vector< comm.Table >();

or

mappingLookupResult = new Vector< ? extends comm.Table >();

Also - are you using Vector for a specific reason? is faster if synchronization is not required. 更快。

Since generics are mainly a compile-time only construct, you can't instantiate the generic type parameter (in this case T of Vector<T> ) based on a String provided at runtime.

It wouldn't make sense anyway: whoever interacts with your Vector won't have the information needed to deal with the vector using the concrete type anyway. If they did, then they could just provide you the Class<? extends Table> Class<? extends Table> directly instead of providing the class name.

However, you can ensure that your vector type parameter has an upper bound of Table . What you need to do depends on how you're actually interacting with the Vector . For example, if you want to put new instances of the type into it, you need to type tableClass :

 Class<? extends Table> tableClass =      
     Class.forName(tableClassName).asSubclass(Table.class);
 Vector<Table> result  = new Vector<Table>();
 result.add(tableClass.newInstance());

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