gpt4 book ai didi

java - 覆盖枚举方法时出现奇怪的行为。 getClass().getInterfaces() 是否正常工作?

转载 作者:行者123 更新时间:2023-11-29 07:48:05 24 4
gpt4 key购买 nike

我会尽量简洁:

考虑界面:

package com.stackoverflow;

public interface Printable {
void print();
}

我创建了一个实现此接口(interface)的枚举。到目前为止一切顺利:

public enum MyEnum implements Printable {
ERROR,
WARNING,
SUCCESS;

@Override
public void print() {
System.out.println("Printed: " +this.name());
}
}

我用以下几行创建了一个main方法:

//OK! Prints 1
System.out.println(ERROR.getClass().getInterfaces().length);

//OK! Prints "Printable" (the name of the interface).
System.out.println(ERROR.getClass().getInterfaces()[0].getSimpleName());

一切都按预期工作,对吗?现在到了奇怪的部分:

public enum MyEnum implements Printable {
ERROR,
WARNING{

//Notice the "@Override", that means that I'm overriding a superclass/interface method! No compiler errors!
@Override
public void print() {
System.out.println("I'm not printable anymore!");
}
},
SUCCESS;

@Override
public void print() {
System.out.println("Printed: " +this.name());
}
}

问题:

为什么重写 print 方法会使 enumInstance.getClass().getInterfaces() 不返回 Printable?在上面的示例中,我知道 WARNING 现在是匿名类的一部分,但是 getInterfaces 不应该返回声明的接口(interface)(在本例中为 Printable)?

//OK! Prints 1
System.out.println(ERROR.getClass().getInterfaces().length);
//NOT OK! Prints 0
System.out.println(WARNING.getClass().getInterfaces().length);

最佳答案

使用下面的循环来理解:

public static void main(String[] args) {
for (MyEnum e : MyEnum.values()) {
System.out.println(e + ".getClass() = " + e.getClass());
}
}

它会打印:

ERROR.getClass() = class com.stackoverflow.MyEnum
WARNING.getClass() = class com.stackoverflow.MyEnum$1
SUCCESS.getClass() = class com.stackoverflow.MyEnum

这意味着 WARNING 实际上是一个匿名类的实例,它扩展了 MyEnum。 getInterfaces() 只返回类声明要实现的接口(interface)(即类声明的 implements 子句中的接口(interface))

关于java - 覆盖枚举方法时出现奇怪的行为。 getClass().getInterfaces() 是否正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com