In this post, we will see how to invoke constructor using reflection in java.
You can retrieve the constructors of the classes and instantiate object at run time using reflection. java.lang.reflect.Constructor
is used to instantiate the objects.
Table of Contents
Instantiate Constructor with no parameters
In case, you want to create object using no args constructor at runtime, you can do it as below.
1 2 3 4 5 6 7 |
Class<?> cl = Class.forName("org.arpit.java2blog.Color"); // Call no-args constructor Object newInstance = cl.newInstance(); System.out.println(newInstance); |
Here,
Class.forName("org.arpit.java2blog.Color")
is used to load the class and get an object of type Class
and we can retrieve a lot of information such as constructors, methods, and annotations etc. at run time with Class
object.
You need to replace org.arpit.java2blog.Color
with classname for which you want to instantiate object at run time.
cl.newInstance()
can be used to create object with no-args constructor at run time.
Instantiate Constructor with parameters
In case, you want to instantiate constructor with parameters, you need to retrieve constructor with parameters and then pass parameters to instantiate it.
1 2 3 4 5 6 7 8 9 10 11 12 |
Class<?> cl = Class.forName("org.arpit.java2blog.Color"); // Call parameterized constructor Class<?>[] type = { String.class,String.class }; // get parameterized constructor which takes 2 Strings as parameters Constructor<?> cons = cl.getConstructor(type); // String arguments Object[] obj = { "Red","#FF0000"}; Object newInstancePC = cons.newInstance(obj); |
- You need to pass
Class[]
togetConstructor()
method and retrieve the instance ofjava.lang.reflect.Constructor
fromcl
. - Pass
Object[]
to cons.newInstance to construct object with passed parameters.
You can also get Parameters types with cons.getParameterTypes()
1 2 3 |
Class[] parameterTypes= cons.getParameterTypes(); |
Let’s see this with an example.
Consider a class named Color
which has two attributes name
and htmlCode
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package org.arpit.java2blog; public class Color { String name; String htmlCode; public Color(String name, String htmlCode) { super(); this.name = name; this.htmlCode = htmlCode; } public Color() { name = "black"; htmlCode = "#000000"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHtmlCode() { return htmlCode; } public void setHtmlCode(String htmlCode) { this.htmlCode = htmlCode; } @Override public String toString() { return "Color [name:" + name + " HtmlCode:" + htmlCode + "]"; } } |
Create main class named ConstuctorReflectionMain
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package org.arpit.java2blog; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class ConstuctorReflectionMain { public static void main(String[] args) { try { Class<?> cl = Class.forName("org.arpit.java2blog.Color"); System.out.println("===================="); System.out.println("Calling default constructor"); System.out.println("===================="); // Call default constructor Object newInstance = cl.newInstance(); System.out.println(newInstance); System.out.println("===================="); System.out.println("Calling parameterized constructor"); System.out.println("===================="); Class<?>[] type = { String.class,String.class }; // get parameterized constructor which takes 2 Strings as parameters Constructor<?> cons = cl.getConstructor(type); // String arguments Object[] obj = { "Red","#FF0000"}; Object newInstancePCObj = cons.newInstance(obj); // cast it to required type Color color=(Color) newInstancePCObj; System.out.println(color); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } } |
When you run above program, you will get below output:
Output:
Calling default constructor
====================
Color [name:black HtmlCode:#000000] ====================
Calling parameterized constructor
====================
Color [name:Red HtmlCode:#FF0000]
As you can see, we are able to instantiate object using java.lang.reflect.Constructor
at run time using reflection.
Constructor parameters for primitive types
In case, you have constructor parameters with primitive types, you can use .class
suffix with that.
For example:
If the parameter type is of int
, then you can use int.class
while getting constructor of that type.
Let’s understand with the help of example:
Consider a class Employee
with attributes: name
and age
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package org.arpit.java2blog; public class Employee { String name; int age; public Employee(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; } } |
Create main class named ConstructorParameterPrimMain
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package org.arpit.java2blog; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class ConstructorParameterPrimMain { public static void main(String[] args) { try { Class<?> cl = Class.forName("org.arpit.java2blog.Employee"); Class<?>[] type = { String.class,int.class }; // get parameterized constructor which takes 2 Strings as parameters Constructor<?> cons = cl.getConstructor(type); // String arguments Object[] obj = { "Arpit",28}; Object newInstanceObj = cons.newInstance(obj); // cast it to required type Employee emp=(Employee) newInstanceObj; System.out.println(emp); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } } |
When you run above program, you will get below output:
Output:
You can also pass Integer.Type
instead of int.class
.
1 2 3 |
Class<?>[] type = { String.class,Integer.Type }; |
Conclusion
You have learnt about how to invoke constructor and instantiate objects at runtime using reflection. We have also seen how to handle primitive type parameters while getting constructor from class.
That’s all about how to invoke constructor using Reflection in java.