Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

The this Class in the documentation is referring to the caller of the getSuperclass() method as far as I understand it.

So if the caller is either the Object class or a primitive type / interface the superclass returned will be null which makes total sense in my opinion.

If you need to find out if Object is a direct parent of your class, you can use

System.out.println(YourObject.class.getSuperclass() == Object.class);

Otherwise you should know that at the end each object inherits Object class. Instead of Object class itself, so .getSuperclass() will return null.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top