Saturday,May9,

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

Abstract Entities ActiveMessaging Amazon SQS Asynchronous mail sending Context Menu Contiuous Integration Deploy Rails Application Deployment by Capistrano Design pattern Ext GWT Ext GWT DnD Framework Filter Grid GWT GXT Chart GXT Editable Grid GXT Example GXT Grid Grouping GXT Tree Filter GlassFish Google App Engine Grid GroupLayout JDO JPA JPQL JTable JavaMail API ListView Local Paging Mapped Superclass Open flash chart Reflection Remote pagination Session Management Strategy pattern XTemplate cruisecontrol.rb filter JTable Row flash chart gxt java reCAPTCHA
Twitter Updates
    follow me on Twitter

    Followers