Java: Unable to use EnumSet within an Enumeration : Initialization error : Tech Research Talent Tree example

前端 未结 2 819
野趣味
野趣味 2020-12-17 17:13

Error:

...
Caused by: java.lang.ExceptionInInitializerError
...
Caused by: java.lang.ClassCastException: 
class com.evopulse.ds2150.TechTrees$BuildingTechTre         


        
2条回答
  •  遥遥无期
    2020-12-17 17:34

    You have a chicken and egg problem. You could refactor your enum to something like this:

    public enum BuildingTechTree {
    
        NONE("NULL"),
        BARRACKS("Barracks"),
        WALLS_SANDBAGS("Sandbag wall"),
        POWERPLANT("Power plant"),
        GUARDTOWER("Guard Tower");
    
        static {
            NONE.trees = EnumSet.noneOf(BuildingTechTree.class);
            BARRACKS.trees = EnumSet.of(NONE);
            WALLS_SANDBAGS.trees = EnumSet.of(NONE);
            POWERPLANT.trees = EnumSet.of(BARRACKS);
            GUARDTOWER.trees = EnumSet.of(BARRACKS);
        }
    
        private String name;
        private Set trees;
    
        private BuildingTechTree(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public Set getTrees() {
            return Collections.unmodifiableSet(trees);
        }
    }
    

    EDIT:

    regarding your second problem: you're accessing a static variable, from a static method. But this variable is initialized when the constructor of the class has been called (which is a huge design problem). Don't use non-final static fields. And don't initialize static fields from instance methods or constructors. That doesn't make sense. You don't set the color that all cars should have when constructing a car. Initialize your static fields statically:

    public class TechTrees {
        private static final Set TECHS_KNOWN =
            EnumSet.of(BuildingTechTree.NONE);
    
        public static boolean researchTech(BuildingTechTree tech) {
            return TECHS_KNOWN.containsAll(tech.requirements));
        }
    }
    

提交回复
热议问题