Here we are going to write a program, how to get the class hierarchy names using Java Reflection mechanism.

Java Reflection Get Class Hierarchy :


package com.onlinetutorialspoint.ref;

public class Reflection_Class_Hierarchy {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("PLEASE PASS THE CLASS NAME..!");
        } else {
            try {
                Class c = Class.forName(args[0]);
                printHierarchy(c);
            } catch (ClassNotFoundException cnfe) {
                System.out.println(args[0] + " DOES NOT EXISTS...");
            }
        }
    }

    static void printHierarchy(Class c) {
        Class c1 = c;
        String cname = c1.getName();
        System.out.println(cname);
        Class sc = c1.getSuperclass();
        while (sc != null) {
            cname = sc.getName();
            System.out.println(cname);
            c1 = sc;
            sc = c1.getSuperclass();
        }
    }
}

Output :

Javac Reflection_Class_Hierarchy.java
java Reflection_Class_Hierarchy 

java.util.ArrayList
java.util.ArrayList
java.util.AbstractList
java.util.AbstractCollection
java.lang.Object

Happy Learning 🙂