Reputation: 97
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?
Upvotes: 2
Views: 224
Reputation: 140319
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
inClassOrInterfaceTypeToInstantiate
denotes an interface,I
, then an anonymous direct subclass ofObject
that implementsI
is declared.
Upvotes: 3
Reputation: 140457
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.
Upvotes: 2
Reputation: 262534
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.
Upvotes: 5