Reputation: 20856
I'm trying to find the hierarchy of the Object - "String" using the below method.
public class test{
public static void main(String[] args){
String x = "Test";
System.out.println(x.getClass().getClass());
}
}
The first x.getclass() return
Output:
class java.lang.String
then -System.out.println(x.getClass().getClass());
Output:
class java.lang.Class
and anything after that yields the same result
System.out.println(x.getClass().getClass().getClass().getClass());
Shouldn't it at some point lead to - java.lang.Object??
Upvotes: 1
Views: 95
Reputation: 124215
Result is correct since you are calling getClass()
on Class
instance. To get parent class you should call getSuperclass()
from Class
instance that represents subclass type.
String x = "Test";
System.out.println(x.getClass().getSuperclass());
Output
class java.lang.Object
Upvotes: 4
Reputation: 308021
x.getClass().getClass()
will always return the class object representing java.lang.Class
for any non-null value x
.
That's because x.getClass()
can only return a Class
object and you're asking that class object what type it is (obviously: Class
).
What you seem to want to try is not x.getClass().getClass()
but x.getClass().getSuperClass()
. Repeating that last part will eventually lead to java.lang.Object
, as you expected (and, if repeated one more time, to null
).
Upvotes: 1