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.