Creating objects through Reflection in Java with Example

In Java, we generally create objects using the new keyword or we use some DI framework e.g. Spring to create an object which internally use Java Reflection API to do so. In this Article, we are going to study the reflective ways to create objects.
There are two methods in Reflection API which we can use to create objects
  1. Class.newInstance()            → Inside java.lang package
  2. Constructor.newInstance()Inside java.lang.reflect package
However there are total 5 ways create objects in Java, if you are not aware of them please go through this article 5 Different ways to create objects in Java with Example.
Both Class.newInstance() and java.lang.reflect.Constructor.newInstance() are known as reflective methods in Java because these two uses reflection API to create the object. And both are not static we can call earlier one on a class level object while latter one needs constructor level object which we can get by the class level object.

Class.newInstance()

The Class class is the most popular class in Java after the Object class. However, this class lies in the java.lang package but plays major role for Reflection API (java.lang.reflect.*).
In order to use Class.newInstance() we first need to get the class level instance of that class for which we want to create objects. We can do this by two ways one is writing complete name of the class and appending .class to it and another is using Class.forName() method, So in below code Employee.class is similar to (Employee) Class.forName("org.programming.mitra.exercises.Employee")
Below code demonstrates how we can create objects using Class.newInstance()
Employee emp = Employee.class.newInstance();
Or
Employee emp = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();

Class.newInstance() internally itself use the Constructor.newInstance() to create the object as we can see in the source code of Class class, notice line no 430 and 442 in below image.



Constructor.newInstance()

In order to use Constructor.newInstance() method we first need to get constructor object for that class and then we can call newInstance() on it to create objects as show below
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
It internally use sun.reflect.ConstructorAccessor class to get the object, which is Oracle's private API.

Difference between Class.newInstance() and Constructor.newInstance()

By name, both methods look same but there are differences between them which we are as following

Due to above reasons Constructor.newInstance() is preferred over Class.newInstance(), that’s why used by various frameworks and APIs like Spring, Guava, Zookeeper, Jackson, Servlet etc.
You can found the complete source code at Github.


Next Post Newer Post Previous Post Older Post Home

4 comments :