Skip to main content

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 present 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 because these two uses reflection API to create the object. Both are not static and we can call earlier one on a class level object while latter one needs constructor level object which we can get by using 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 a major role in Reflection API (java.lang.reflect.* package).

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.

Creating objects through Reflection in Java with Example

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 shown 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

1. Class.newInstance() can only invoke the no-arg constructor,
        Constructor.newInstance() can invoke any constructor, regardless of the number of parameters.

2. Class.newInstance() requires that the constructor should be visible,
       Constructor.newInstance() can also invoke private constructors under certain circumstances.

3. Class.newInstance() throws any exception (checked or unchecked) thrown by the constructor,
        Constructor.newInstance() always wraps the thrown exception with an InvocationTargetException.

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 find complete code on this Github Repository and please feel free to provide your valuable feedback.

Comments

  1. Replies
    1. Sorry Buddy but I do not good knowledge of C++

      Delete
  2. "Constructor.newInstance() can also invoke private constructors under certain circumstances" what kind of circumstances?

    ReplyDelete
    Replies
    1. This code will do the trick, it will change the access modifier of the constructor to public
      try {
      Constructor constructor = Singleton.class.getDeclaredConstructor();
      constructor.setAccessible(true);
      singleton = constructor.newInstance();

      // Constructor constructor = (Constructor) Class.forName("com.example.bloder.deck.SingletonActivity").getConstructor();
      // singleton = constructor.newInstance();
      } catch (InstantiationException e) {
      e.printStackTrace();
      } catch (IllegalAccessException e) {
      e.printStackTrace();
      } catch (InvocationTargetException e) {
      e.printStackTrace();
      } catch (NoSuchMethodException e) {
      e.printStackTrace();
      }

      Delete

Post a Comment

Popular posts from this blog

Why Single Java Source File Can Not Have More Than One public class

According to Java standards and common practices we should declare every class in its own source file. And even if we declare multiple classes in the single source file (.java) still each class will have its own class file after compilation. But the fact is that we can declare more than one class in a single source file with below constraints, Each source file should contain only one public class and the name of that public class should be similar to the name of the source file. If you are declaring the main method in your source file then main should lie in that public class If there is no public class in the source file then main method can lie in any class and we can give any name to the source file. If you are not following 1st constraint then you will receive a compilation error saying “ The public type A must be defined in its own file ”.  While if you are not following the second constraint you will receive an error “ Error: Could not find or load main class User ” after exec

AutoWiring Spring Beans Into Classes Not Managed By Spring Like JPA Entity Listeners

In my previous article JPA Auditing: Persisting Audit Logs Automatically using EntityListeners , I have discussed how we can use Spring Data JPA automate Auditing and automatically create audit logs or history records and update CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate properties. So in order to save history records for our File entity, we were trying to auto-wire EntityManager inside our FileEntityListener class and we have come to know that we can not do this. We can not inject any Spring-managed bean in the EntityListener because EntityListeners are instantiated by JPA before Spring inject anything into it. EntityListeners are not managed Spring so Spring cannot inject any Spring-managed bean e.g. EntityManager in the EntityListeners. And this case is not just with EntityListeners, you can not auto wire any Spring-managed bean into another class (i.e. utility classes) which is not managed by Spring. Because it is a very common problem and can also arise with other c

How Does JVM Handle Method Overloading and Overriding Internally

In my previous article Everything About Method Overloading Vs Method Overriding , I have discussed method overloading and overriding, their rules and differences. In this article, we will see How Does JVM Handle Method Overloading And Overriding Internally, how JVM identifies which method should get called. Let’s take the example of parent class  Mammal and a child  Human classes from our previous blog to understand it more clearly. public class OverridingInternalExample { private static class Mammal { public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); } } private static class Human extends Mammal { @Override public void speak() { System.out.println("Hello"); } // Valid overload of speak public void speak(String language) { if (language.equals("Hindi")) System.out.println("Namaste"); else System.out.println("Hello"); } @