Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an ArrayList of Classes?

I have some classes (Car, Motorcycle, Train ... etc) that extends from class Vehicle. From another Class I need to create an ArrayList of Classes for access only to those that inlude the ArrayList.

The concept is similar to this, but obviously it doesn't work;

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

How can I solve it ? Thanks

like image 499
Fischer Avatar asked Oct 25 '11 18:10

Fischer


People also ask

Can we make an ArrayList of class?

Build an ArrayList Object and place its type as a Class Data. Define a class and put the required entities in the constructor. Link those entities to global variables. Data received from the ArrayList is of that class type that stores multiple data.

How do you declare an ArrayList in a class?

You can declare the ArrayList within the class, but then add items within the constructor. public class System{ ArrayList<Product> list = new ArrayList<Product>(); public System(){ list. add(param1, param2, param3); //add stuff here. } }

How do you create an ArrayList of objects?

You can simply use add() method to create ArrayList of objects and add it to the ArrayList. This is simplest way to create ArrayList of objects in java.

How do you create an ArrayList list?

Convert list To ArrayList In Java. ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.


2 Answers

Most answers follow your suggestion of using Class.forName(), though that's not necessary. You can "call" .class on the 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 for your need the list would be of type Class<? extends Vehicle>

like image 54
Noel M Avatar answered Nov 03 '22 20:11

Noel M


If you're going to use the class loader (Class.forName), you need to use the fully qualified class name, i.e. Class.forName("com.package.Train");, exactly as you would reference it from the command line.

like image 3
Dave Avatar answered Nov 03 '22 19:11

Dave