[英]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. 事实是,即使Object
没有超类, s.getClass().getSuperclass()
也永远不会返回null
。
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
是一个Class
实例。
s.getClass()
therefore always returns Class.class
, which has a superclass. s.getClass()
因此总是返回Class.class
,它具有超类。
Here you assign a Class to s
: 在这里,您将类分配给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. Class对象的类为Class.class
其getSuperclass
返回Object.class
因此循环条件的值为true。
Then you assign s
to Object.class
: 然后将s
分配给Object.class
:
s = s.getClass().getSuperclass();
Whose class is Class.class
and has a super class. 谁的班级是Class.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 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.