Program to demonstrate how to find Superclasses of a given class dynamically using Java Reflection API.
Output of the program :
package com.hubberspot.reflection; // Create Three Java classes such as // Animal which extends Object class Animal { } //Dog which extends Animal class Dog extends Animal { } // GermanShepherd which extends Dog class GermanShepherd extends Dog { } public class SuperClassFinding { public static void main(String[] args) { // Get the instance of Class for the type // GermanShepherd Class childClass = GermanShepherd.class; // Get the instance of Class for the supertype // of the class GermanShepherd. The Class instance // for super-class is been found by calling // getSuperclass() method of class Class. Class superClass = childClass.getSuperclass(); // Loops over the hierarchy of classes in examples // till reaching the top most class Object while(superClass != null) { // In order to get name of the superclass // we call method getName over the Class instance // of Superclass String className = superClass.getName(); // Prints over the console System.out.println("The Super Class for " + childClass.getName() + " is : \n" + className); childClass = superClass; superClass = childClass.getSuperclass(); System.out.println(); } } }
Output of the program :