How to create an instance of a class at runtime using Java Reflection

Java Reflection gives us the facility of creating an instance of any class at run time. In our ERP project it helps us a lot to solve some critical problems.

First create a class using the class name then use the class.newInstance method
to create an instance of that class.


javax.swing.JPanel newPanel = null;

String className= "com.commlinkinfotech.cbs.appclient.gl.ChartsOfAccount";

Class class = Class.forName(className);

//we know that the ChartsOfAccount is a JPanel class so cast this to JPanel
newPanel = (JPanel) class.newInstance();


But if the constructor of your class takes some parameters then what will you do?

You have to create an array of your argument class. Use this to create a constructor of your class using the class.getConstructor method. Now call the constructor.newInstance method with the value of the arguments and it gives you an instance of the class.


javax.swing.JPanel newPanel = null;

String className= "com.commlinkinfotech.cbs.appclient.gl.ChartsOfAccount";

//create an array of parameter classes
Class[] types = new Class[] { String.class };

Class class = Class.forName(className);
//create a constructor with the types array
Constructor constructor = class.getConstructor(types);

//create an array of argument values
Object[] args = new Object[] {new String("Hello")};

//now use ther args array to create an instance
newPanel = (JPanel) constructor .newInstance(args);

1 comments:

Anonymous May 9, 2013 at 6:53 PM  

tell me how can i find my java classes path like
"com.commlinkinfotech.cbs.appclient.gl.ChartsOfAccount";
i want to extract java classes information like extends or isinterface....

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers