Java Reflection Get Class Hierarchy

By |2018-03-21T21:17:48+05:30June 22nd, 2016|java programs|

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment