Steve Chambers Steve Chambers - 27 days ago 6
Java Question

Why does Class.getSuperclass() sometimes return Object.class?

According to the Class.getSuperclass() documentation:


Returns the Class representing the superclass of the entity (class,
interface, primitive type or void) represented by this Class. If this
Class represents either the Object class, an interface, a primitive
type, or void, then null is returned.


But I'm sometimes seeing
Object.class
being returned (using jdk1.7.0_45) - so am having to check for it separately:

final Class<?> superclass = modelClass.getSuperclass();
if ((superclass != null) && (Object.class != superclass)) {
// Do stuff with superclasses other than Object.
}


Is this a Java bug? Is there a better way of checking whether
superclass
is an
Object
?

Answer

The documentation says that if your class is java.lang.Object, then its getSuperclass is going to return null. In other words, if you do this

Class objSuper = Object.class.getSuperclass();

then objSuper would be null; this is precisely what's happening (demo).

It appears, however, that your modelClass is not java.lang.Object, and it is also not a primitive or an interface. Therefore, returning java.lang.Object makes perfect sense, because all classes implicitly inherit from it.