Java Enum类的文档声明如下getDeclaringClass:
返回与此枚举常量的枚举类型对应的Class对象.当且仅当e1.getDeclaringClass()== e2.getDeclaringClass()时,两个枚举常量e1和e2具有相同的枚举类型.(此方法返回的值可能与Object.getClass()方法返回的值不同,对于具有常量特定类主体的枚举常量.)
我不明白何时getClass和getDeclaringClass不同.有人可以提供一个例子和解释吗?
在撰写另一个答案时调查堆栈跟踪差异时,我遇到了一个我不理解的行为.考虑以下测试程序(这是我可以缩小它的范围):
interface TestInterface <U> {
void test (U u);
}
static class Test <T extends Test<T>> implements TestInterface<T> { // line 11
@Override public void test (T t) {
throw new RuntimeException("My exception"); // line 13
}
}
static class TestA extends Test<TestA> { }
static class TestB extends Test<TestB> { }
public static void main (String[] args) throws Exception {
try {
Test a = new TestA();
Test b = new TestB();
a.test(b);
} catch (Exception x) …Run Code Online (Sandbox Code Playgroud)