0

Possible Duplicate:
Is it possible to use Java Reflection to print out attributes of the parent class?

Hi, is it possible to use Java Reflection or various techniques to check if a class has a parent class?

This thought came as something for a need to create a utility class that takes in an object, print out its attributes, and if a parent class exists, to print out the attributes of the parent class.

Edit I meant to ask if there was a way to keep checking if a class had a mother class all the way up to the Object class.

Community
  • 1
  • 1
Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
  • What's the difference between this question and [the one you asked ~20 minutes ago](http://stackoverflow.com/questions/6099128)? – Matt Ball May 23 '11 at 15:34
  • 1
    ... every class has a parent class - except for `java.lang.Object` ... – Andreas Dolk May 23 '11 at 15:38
  • Sorry i edited the question slightly. The idea is to ask if there was a technique to keep traversing "upwards" eventually to the Object and printing attributes belonging to each class along the way. – Oh Chin Boon May 23 '11 at 15:38
  • 2
    @Chin, there is indeed a technique for this, it is called a _loop_ ;-) Honestly, the accepted answer to your previous question shows you how to get the direct superclass of a class, and that's all you need to solve this problem. – Péter Török May 23 '11 at 15:41
  • @Peter - a *loop*? Looks more like a job for Mr. Recursion ;) – Andreas Dolk May 23 '11 at 15:45
  • @Andreas_D, either of them can do the job, but I thought the Loop sisters are more widely known than their somewhat mysterious cousin :-) – Péter Török May 23 '11 at 15:48

2 Answers2

3

Use this:

Class<?> superClass = MyClass.class.getSuperClass();

All superclasses:

public static void printSuperClass(Class<?> clazz) {
  if (clazz == null) return;

  Class<?> superclass = clazz.getSuperClass();
  System.out.println(clazz.getName() + " extends " + superclass.getName());
  printSuperClass(superclass);
}
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
1

You can use a for loop to walk up the parent classes.

for(Class clazz=object.getClass(); clazz!=null; clazz=clazz.getSuperClass())
    System.out.println(clazz);

Note: Object, primitives, interfaces and array's all have null as a superclass.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130