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 there other good alternatives?
I would use an interface which these instances all share, then you can use any number of enums or load them from another data source such as a file or database.
1300 values? Good god, who thought that was a good idea? Did it not occur to someone after 100 that it was getting too big?
There's no good way around it that I can see. Get a shovel and start combining them into more cohesive sub-enums.
Here's a question: How are they used? If they are part of your application configuration, I'd recommend moving them to a database rather than keeping them in code. They'll be more flexible that way.
you can break them up like:
import java.util.*;
interface Children {
Set<Enum<?>> children();
}
enum Dog implements Children {
myDog,yourDog;
Dog() {
this(null);
}
Dog(Set<Enum<?>> children) {
this.children=children;
}
@Override public Set<Enum<?>> children() {
return children!=null?Collections.unmodifiableSet(children):null;
}
Set<Enum<?>> children;
}
enum Animal implements Children {
cat,dog(EnumSet.allOf(Dog.class));
Animal() {
this(null);
}
Animal(Set children) {
this.children=children;
}
@Override public Set<Enum<?>> children() {
return children!=null?Collections.unmodifiableSet(children):null;
}
Set<Enum<?>> children;
}
enum Thing implements Children {
animal(EnumSet.allOf(Animal.class)),vegetable,mineral;
Thing() {
this(null);
}
Thing(Set children) {
this.children=children;
}
@Override public Set<Enum<?>> children() {
return children!=null?Collections.unmodifiableSet(children):null;
}
Set<Enum<?>> 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);
}
}
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