简体   繁体   中英

Java reflection gets superclass got unexpected result

While learning java reflection, I got some problem when testing getSuperclass()

Below is my test code:

System.out.println(java.io.Closeable.class.getSuperclass());

In my expectation, this line shall print something like AutoClosable because this is the class which Closable extends from. However this turns out to be null . I tried to explain this as Closable locates in java.io while AutoClosable locates in java.lang and getSuperclass() would only search in the package scope.

But this explanation does not make sense if I write like this:

Closeable closeable = () -> {

    };
System.out.println(closeable.getClass().getSuperclass());

The code above results in class java.lang.Object . The result makes this problem more peculiar and hard to understand.

How does java implements this getSuperclass() method and why does not this method return the result which corresponds to its name?

Neither Closeable nor AutoCloseable are classes, they are both interfaces.

getSuperclass only returns super-classes, not super-interfaces. If called on something that is not a class itself (such as an interface, or a primitive type), the method returns null .

You may want to call getInterfaces instead.

Closeable is an interface, it has no superclass, only superinterfaces.

As it says in the documentation of getSuperclass() :

If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.

Closeable closeable = () -> {

};

is effectively creating concrete class which implements Closeable : Closeable has a single abstract method, close() , which you are implementing with an empty body. This is effectively the same as writing:

Closeable closeable = new Closeable() {
  @Override public void close() {}
}

This class does have a superclass, because all classes except Object have a superclass. That superclass is Object , per the spec :

If the Identifier in ClassOrInterfaceTypeToInstantiate denotes an interface, I , then an anonymous direct subclass of Object that implements I is declared.

That method getSuperClass says:

Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.

In your case, the super class is Object. Because you are looking at a class instance.

Meaning: in your second example, you created a lambda, basically: an anonymous inner class .

To gather information about implemented (or extended) interfaces, use getInterfaces .

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