Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
Steve Chambers Avatar asked Nov 25 '13 15:11

Steve Chambers


People also ask

Can a class be null in Java?

null is not a class.

What are classes in Java?

A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.


1 Answers

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.

like image 111
Sergey Kalinichenko Avatar answered Sep 19 '22 01:09

Sergey Kalinichenko