TrewTzu TrewTzu - 1 month ago 9
Java Question

Creating object from enum reference

If I have a standard enum (in this example a representation of a list of buildings) such as this:

public enum BuildingType {
farm, shop, house
}


and a function that creates objects based on a "building" superclass such as:

public void addBuilding(BuildingType bType) {
Building b = new Building();
b.start();
}


All of my subclasses have names matching the BuildingType enum.
Is there a way that I can use my enum parameter to set the class of object b without a class statement?

clearly incorrectly, but something like this

Building b = new bType(); //using the argument


Thanks as always.

Answer

You can define an enum that is also a factory:

public enum BuildingType {
    farm(Farm.class),
    shop(Shop.class),
    house(House.class);
    private Class<? extends Building> clazz;
    private BuildingType(Class<? extends Building> clazz) {
        this.clazz = clazz;
    }

    public Building createBuilding() {
        try {
            return clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(clazz + " has no default constructor");
        }
    }
}

Or slightly more code, but avoiding reflection, make the enum class an abstract factory and let the instances be factories:

public enum BuildingType {
    farm() {
        public Building createBuilding() {
            return new Farm();
        }
    },
    shop() {
        public Building createBuilding() {
            return new Shop();
        }
    },
    house() {
        public Building createBuilding() {
            return new House();
        }
    };

    public abstract Building createBuilding();
}

Either way, to use:

public void addBuilding(BuildingType bType) {
   Building b = bType.createBuilding();
   b.start();
}