有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

在JLS中阅读此part

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

共 (1) 个答案

  1. # 1 楼答案

    JLS是准确的,但您对^{}返回的内容做出了错误的假设:

    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.