简体   繁体   中英

Object.getClass().getSuperclass() not returning null?

I have a function

public void get(Object s) {

  while (s.getClass().getSuperclass() != null) {
      s = s.getClass().getSuperclass();
  }
}

The thing is that the s.getClass().getSuperclass() never returns null , even though Object has no superclass.

I don't understand why this is happening, although I debugged the project several times.

After the first time you run your loop, s is a Class instance.

s.getClass() therefore always returns Class.class , which has a superclass.

Here you assign a Class to s :

s = s.getClass().getSuperclass();

Then the loop condition is:

s.getClass().getSuperclass();

A Class object's class is Class.class whose getSuperclass returns Object.class so the loop condition evaluates to true.

Then you assign s to Object.class :

s = s.getClass().getSuperclass();

Whose class is Class.class and has a super class. Repeat ad infinitum.

Use a different variable for the class.

Class<?> cls = s.getClass().getSuperclass();
while(cls != null) {
    cls = cls.getSuperclass();
}

Why your code won't work was explained by SLaks

What you want is this:

public void get(Object s)
{
    Class<?> buffer = s.getClass();

    while (buffer != null)
    {
        System.out.println(buffer);
        buffer = buffer.getSuperclass();

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM