Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
Yifeng Avatar asked Dec 07 '25 14:12

Yifeng


2 Answers

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.

like image 82
Thilo Avatar answered Dec 09 '25 04:12

Thilo


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.

like image 20
Andy Turner Avatar answered Dec 09 '25 04:12

Andy Turner