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
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.
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. } }
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With