gpt4 book ai didi

java - 从类和接口(interface)重新继承静态字段

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:25 24 4
gpt4 key购买 nike

interface A {
public static String name = "A";
}
interface B {
public static String name = "B";
}
class X implements A { }
class Y extends X implements B { }
public void test_getField() {
try {
assertEquals(B.class.getField("name"), Y.class.getField("name"));
} catch (NoSuchFieldException e) {
fail("Got exception");
}
}

为什么 Y.class.getField("name") 返回 B.name 而不是 A.name?Java规范中有没有答案?

最佳答案

将在父类(super class)之前搜索直接超接口(interface),参见 doc getField 的:

The field to be reflected is determined by the algorithm that follows.Let C be the class represented by this object:

If C declares a public field with the name specified, that is thefield to be reflected.

If no field was found in step 1 above, thisalgorithm is applied recursively to each direct superinterface of C.The direct superinterfaces are searched in the order they weredeclared.

If no field was found in steps 1 and 2 above, and C has asuperclass S, then this algorithm is invoked recursively upon S. If Chas no superclass, then a NoSuchFieldException is thrown.

关于java - 从类和接口(interface)重新继承静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49998880/

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