gpt4 book ai didi

java - 为什么我的接口(interface)没有 JLS 声明的方法?

转载 作者:行者123 更新时间:2023-11-30 07:54:50 24 4
gpt4 key购买 nike

阅读此 part在 JLS 中:

If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

我试图通过反射确认这些方法的存在,但只有 ok 方法出现。

为什么不显示隐式声明的方法?我怎样才能看到它们?

interface C {
public void ok();
}
public class Test{
public static void main(String[] args) {
for (Method m : C.class.getMethods()) {
System.out.println(m.getName()+":"+Modifier.isAbstract(m.getModifiers()));
}
}
}

输出:

ok:true

最佳答案

JLS 是准确的,但您对 Class.getMethods() 的假设不正确返回:

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

...

If this Class object represents an interface then the returned array does not contain any implicitly declared methods from Object. Therefore, if no methods are explicitly declared in this interface or any of its superinterfaces then the returned array has length 0.

关于java - 为什么我的接口(interface)没有 JLS 声明的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669683/

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