Java Reflection Get Constructor Information

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

Here we are going to write a program, how to get the Constructor Information using Java Reflection mechanism.

Get Constructor Information :


package com.onlinetutorialspoint.ref;

public class Reflection_Constructor_Info {
    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]);
                printConsts(c);
            } catch (ClassNotFoundException cnfe) {
                System.out.println(args[0] + " DOES NOT EXISTS...");
            }
        }
    }

    static void printConsts(Class c) {
        java.lang.reflect.Constructor Cons[] = c.getConstructors();
        System.out.println("NUMBER OF CONSTRUCTORS = " + Cons.length);
        System.out.println("NAME OF THE CONSTRUCTOR : " + c.getName());
        for (int i = 0; i < Cons.length; i++) {
            System.out.print(c.getName() + "(");
            Class cp[] = Cons[i].getParameterTypes();
            for (int j = 0; j < cp.length; j++) {
                System.out.print(cp[j].getName() + ")");
            }
            System.out.println("\b" + ")");
        }
    }
}

Output :

javac Reflection_Constructor_Info.java
java Reflection_Constructor_Info 
java.awt.TextArea
NUMBER OF CONSTRUCTORS = 5
NAME OF THE CONSTRUCTOR : java.awt.TextArea
java.awt.TextArea(java.lang.String)int)int)
java.awt.TextArea(java.lang.String)int)int)int)
java.awt.TextArea)
java.awt.TextArea(java.lang.String)
java.awt.TextArea(int)int)

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