중복 코드가 없는지 확인하기 위해 enum의 상태를 확인하고 싶습니다. 예를 들어 아래의 enum을 고려하십시오. 자바 열거 형의 상태를 확인하는 방법은 무엇입니까?
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을 중단시키고 싶지만 그렇게하기 쉽지 않습니다.
catch(Throwable e)
이 모든 것을 잡을 것이기 때문에 예외를 throw하는 것은 효과가 없습니다.
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");
}
}
}
단위 테스트를 작성하여 열거 형 정의가 양호하고 중복 코드가 없음을 증명할 수 있습니다. 그러나 일종의 enum에 고유 한 코드가없는 경우 실행되지 않도록 자체 테스트 및 어리석은 증명을 수행하는 방법이 있습니까?
'catch (Throwable e) {'** ** 절대로 이것을하지 마십시오! – Doorknob
@Doorknob'catch (Throwable e)'는 애플리케이션 서버가 모든 예외 처리기에서 범용 캐치 (catch)로 수행 할 수있는 기능입니다. 열거 형이 중복되면 프로그램을 실패하는 방법을 원합니다. – ams
좋아, 그럼 for (;;) {}'? : P – Doorknob