Java: Using getConstructor to access the constor of a class dynamically

Google+ Pinterest LinkedIn Tumblr +

Here we are providing a simple code example on how to access a specific java constructor using reflection.

// First load the class from a string using Class.forName.
Class classType = Class.forName( “com.examplesource.MyClass” );

// Now create a Constructor object (java.reflect.Constructor) by
// passing an array of class objects (note you can use int.class, for example
// for primitives.
Constructor constructor = classType.getConstructor(new Class[] { String.class, Integer.class } );

// Create a new instance of the object by passing an array of Objects
// to newInstance
MyClass myObject = (MyClass) constructor.newInstance( new Object[] {myStringObj, 10} );

Below are a few useful links that may also come in handy if the above example didn’t solve your problem:
http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getConstructor(java.lang.Class…)
http://www.idevelopment.info/data/Programming/java/reflection/ReflectionDemo.java

Share.

About Author

Leave A Reply