Is it possible to list, inside a class, all its static fields automatically, i.e., without explicitly adding them to a list myself?
For example: I have a base class Vehicle
that contains a number of class fields that are derived classes (Car
, Truck
, Van
). How can I get the field VEHICLES
populated without having to add each Car
, Truck
, etc. manually? Is this possible?
public class Vehicle {
public static final Car a = new Car(...);
public static final Car b = new Car(...);
public static final Truck c = new Truck(...);
...
public static final Van d = new Van(...);
public static FINAL List<Vehicle> VEHICLES;
static {
VEHICLES = new ArrayList<>();
// Add all static fields here
}
And, more specifically, would I be able to list per derived class, like so
public static FINAL List<Car> CARS; // populate with all static fields of class Car
public static FINAL List<Truck> TRUCKS; // populate with all static fields of class Truck
...
I have done some searching, and it seems that reflection might be the way to go (for example, this and this question are in the right direction) - but I cannot figure out how to 'translate' the Fields into objects and add them (if possible at all):
public static Field[] fields;
static {
fields = Vehicle.class.getDeclaredFields();
for (Field f : fields) {
VEHICLES.add(...); // to add any Vehicle
if (f.getType().isInstance(Car.class)) {
CARS.add(...); // to add all Cars
}
}
}
Am I way off, and should it be done differently altogether? Or is this not possible, or maybe even a code smell?