Breaking up a large Java enum

前端 未结 4 2066
时光取名叫无心
时光取名叫无心 2020-12-18 06:42

What is the recommended practice for taking a Java enum that has say 1300 values and putting it into organized groups? I know you can\'t just extends the enum group, so are

4条回答
  •  悲哀的现实
    2020-12-18 07:45

    you can break them up like:

    import java.util.*;
    interface Children {
        Set> children();
    }
    enum Dog implements Children {
        myDog,yourDog;
        Dog() {
            this(null);
        }
        Dog(Set> children) {
            this.children=children;
        }
        @Override public Set> children() {
            return children!=null?Collections.unmodifiableSet(children):null;
        }
        Set> children;
    }
    enum Animal implements Children {
        cat,dog(EnumSet.allOf(Dog.class));
        Animal() {
            this(null);
        }
        Animal(Set children) {
            this.children=children;
        }
        @Override public Set> children() {
            return children!=null?Collections.unmodifiableSet(children):null;
        }
        Set> children;
    }
    enum Thing implements Children {
        animal(EnumSet.allOf(Animal.class)),vegetable,mineral;
        Thing() {
            this(null);
        }
        Thing(Set children) {
            this.children=children;
        }
        @Override public Set> children() {
            return children!=null?Collections.unmodifiableSet(children):null;
        }
        Set> children;
    }
    public class So8671088 {
        static void visit(Class clazz) {
            Object[] enumConstants = clazz.getEnumConstants();
            if (enumConstants[0] instanceof Children) for (Object o : enumConstants)
                visit((Children) o, clazz.getName());
        }
        static void visit(Children children, String prefix) {
            if (children instanceof Enum) {
                System.out.println(prefix + ' ' + children);
                if (children.children() != null) for (Object o : children.children())
                    visit((Children) o, prefix + ' ' + children);
            } else
                System.out.println("other " + children.getClass());
        }
        public static void main(String[] args) {
            visit(Thing.animal," ");
            visit(Thing.class);
        }
    }
    

提交回复
热议问题