RoiEX RoiEX - 5 months ago 8
Java Question

Can enums be non static?

I have the following public enum:

public enum CommandObject {
STRING/*etc.*/;
private Collection<String> validOptions = new ArrayList<>();

protected Collection<String> getValidOptions() {
return validOptions;
}

protected boolean hasValidOptions() {
return !validOptions.isEmpty();
}

protected CommandObject addValidOption(String option) {
validOptions.add(option);
return this;
}

public static CommandObject argsetOf(String... args) {
CommandObject result = STRING;
for (String option : args) {
result.addValidOption(option);
}
return result;
}
}


but it seems, that
getValidOptions()
returns always the same collection no matter what instance I call.

For example when calling
argsetOf("hi")
and
argsetOf("bye")
the collection always consists of
["hi","bye"]
.

Does somebody know any workaround for this? I need this enum to have a "non static" attribute.

It doesn't need to be an enum, but should still be simple to use.

Answer

Enums are always static, implicitly.

A workaround here might be to store the collections externally to the enum, e.g. a non-static map externally to the enum, with the enum values as keys:

Map<CommandObject, Collection<String>>

Then you can have as many separate instances of this map as you like, but are still associating the collections with a particular enum value.

Comments