我希望能够验证枚举的状态以确保没有重复的代码。例如考虑下面的枚举。
public enum UniqueCodes {
    A(1), B(2), C(3), D(1);
    private final int value;
    static {
        UniqueCodes[] values = UniqueCodes.values();
        Map<Integer, Boolean> map = new HashMap<>();
        for (UniqueCodes code : values) {
            if (map.get(code.value) == null) {
                map.put(code.value, true);
            } else {
                String msg = String.format(
                        "%s enum contains a non unique code %s",
                        UniqueCodes.class.getName(), code.value);
                System.err.println(msg);
                try {
                    System.exit(-1);
                } catch(SecurityException e) {
                    System.err.println("Really Bad things are going to happen to the application");
                    // what can I do here to crash the JVM 
                }
            }
        }
    }
    private UniqueCodes(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
}
想象一下上面分配了 100 多个代码的枚举,并且您想确保没有枚举定义包含重复值。如果检测到重复值,我想使 JVM 崩溃,但这并不容易。抛出异常无效,因为 acatch(Throwable e)将捕获所有内容。
public class Main {
    public static void main(String[] args) {
        try { 
            System.out.println(UniqueCodes.A);
        } catch(Throwable e) {
            System.out.println("Invalid Enum exception caught");
        }
    }
}
我可以写一个单元测试来证明枚举定义是好的,没有重复的代码。但是有没有办法让它自我测试和万无一失,这样如果枚举没有唯一代码,事情就不会运行?