質問

I'm making a program that has an enum that us used for a list of types but I want it to have the possibility of being expanded later at runtime and am not sure what is the best way to do this is. The only ways I have been able to think of are using arrays of classes in place of the enum which I don't want to do as I would loose the simplicity of the enum.

役に立ちましたか?

解決

Enums are supposed to be completely static enumerations, therefore you must be able to know the exact values the enum covers at compile time.

You could generate the java file at compile time allowing for a bit more flexibility over the values, although this would be rather over the top.

Your best bet would be:

1) To use a class, potentially with a set of predefined instances, so that new instance of said class can be created at runtime.

or

2) To create an interface that an enum containing the default values implements, allowing new instances to be created at runtime, whilst retaining some form of enum structure.

他のヒント

Java enums cannot be expanded/extended at runtime. They are more like constants. If you need extendable enums, maybe enum is not the right concept for you!

Consider using a simple class that you instantiate at runtime.

If you can't know all values that needs to be there at compile time, I'd just use strings. If you want to associate attributes or behaviors to it, you can use a map. This is fairly common in Java. Also in python, people use strings for enums.

Java 7 made switch statement work on strings, which IMO is a move to support this use of strings.

For an example of such use in Java, see this: https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/telnet/TelnetClientInitializer.java

Enumerations are fixed at compile time. How exactly would you "use the simplicity"? You can't for example write a switch command using constants that are not known in advance.

If the point is to branch based on the type of something, you can use classical OO decomposition (create methods in every type in the list and let polymorphism select the correct branch) or use a HashMap from class objects to functional objects or strategy implementations.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top