How to create ArrayList classes?

I have several classes ( Car , Motorcycle , Train ... etc.) that extend from class Vehicle . From another class, I need to create an ArrayList classes to access only those that include an ArrayList .

The concept is similar to this, but obviously it does not work;

 ArrayList<Class> vehicleType=new ArrayList<Class>(); vehicleType.add(Class.forName("train")); 

How can i solve this? Thanks

+7
source share
5 answers

Most answers follow your suggestion to use Class.forName() , although this is optional. You can "call" .class type name.

Take a look at this JUnit test:

 @Test public void testListOfClasses() { List<Class<?>> classList = new ArrayList<Class<?>>(); classList.add(Integer.class); classList.add(String.class); classList.add(Double.class); assertTrue("List contains Integer class", classList.contains(Integer.class)); } 

I would expect your list to be of type Class<? extends Vehicle> Class<? extends Vehicle>

+8
source

If you intend to use the class loader ( Class.forName ), you need to use the fully qualified class name, i.e. Class.forName("com.package.Train"); , just like you reference it from the command line.

+3
source

Try:

 ArrayList<Class<? extends Vehicle>> vehicleType=new ArrayList<? extends Vehicle>(); vehicleType.add(Train.class); 

He will ensure that all classes added to vehicleType extend Vehicle . And this Train class really exists.

It is rarely necessary to use classes this way. Try to find an easier way to solve your problem.

+2
source

Class.forName ("Train"), maybe? Case insensitive?

+1
source

If "train" is a simple class name, then this will complete the task

vehicleType.add (Class.forName (train.class.getName ()));

In any case, until you tell us what the error message (or exception) is, we cannot help further.

0
source

All Articles