Java Programs

Java Reflection Get Class Hierarchy

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

Java Reflection Get Class Hierarchy :

Reflection_Class_Hierarchy.java
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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment