地图的传统实现<字符串,枚举(<&燃气轮机&燃气轮机;处理多个枚举类的复杂性很小。静态最终映射实例在接口中定义,并在所有枚举中共享。
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
class Main {
public static void main(final String[] args) {
// Enum classes must be loaded
loadEnums();
System.out.println(X.get("FIELD1B"));
((X) () -> "FIELD1B").add(); // Attempt to pollute the map is blocked
System.out.println(X.get("FIELD1B"));
}
private static void loadEnums() {
IntStream.range(1, 10).mapToObj(n -> Main.class.getPackageName() + ".Main$Field" + n).forEach(Main::loadEnum);
}
private static void loadEnum(String name) {
try {
Class.forName(name);
} catch (ClassNotFoundException e) {
}
}
/**
* All enums implement this marker interface and therefore share access to a static map from the name of the enum to its value.
*/
interface X {
Map<String, X> map = new HashMap<>();
/**
* This shared method uses enum's name method to get enum's string representation.
*/
default void add() {
if (this instanceof Enum<?>) {
map.put(name(), this);
}
}
static X get(String key) {
return map.get(key);
}
/**
* This method is always overwritten by each enum because all enums have a name() method.
*/
String name();
}
enum Field1 implements X {
FIELD1A, FIELD1B, FIELD1C;
// We have to call add() to place each enum value in the shared map
Field1() {
add();
}
}
enum Field2 implements X {
FIELD2A, FIELD2B, FIELD2C;
Field2() {
add();
}
}
}