简体   繁体   中英

Why doesn't my interface have the methods the JLS says it declares?

Reading this part in 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.

I tried to confirm the existence of these methods through reflection, but only the ok method shows up.

Why aren't the implicitly declared methods showing up? How can I see them?

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()));
        }
    }
}

Output:

ok:true

The JLS is accurate, but you've made an incorrect assumption about what Class.getMethods() returns:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM