Java Reflection: Create Objects

We can use newInstance API of java.lang.reflect.Constructor to create Objects. We can pass initialization parameters to the parameterized Constructors.

Instantiate a new object without no args constructor

Class<ReflectionCreateObjects> clazz = ReflectionCreateObjects.class;
Constructor<ReflectionCreateObjects> constructor = clazz.getConstructor();
ReflectionCreateObjects obj = constructor.newInstance();

Instantiate a new object with parameterized constructor

Class<ReflectionCreateObjects> clazz = ReflectionCreateObjects.class;
Constructor<ReflectionCreateObjects> constructor1 = clazz.getConstructor(String.class);
ReflectionCreateObjects obj1 = constructor1.newInstance("testVar");

Instantiate a new object with Class object

Please note that Class.newInstance() can only invoke the no-arg constructor.

Class<ReflectionCreateObjects> clazz = ReflectionCreateObjects.class;
ReflectionCreateObjects obj2 = clazz.newInstance();
package com.java.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectionCreateObjects {

    @Override
    public String toString() {
        return "ReflectionCreateObjects [var=" +
            var +"]";
    }

    private String
    var;

    public ReflectionCreateObjects(String
        var) {
        this.var =
            var;
    }

    public ReflectionCreateObjects() {}

    public static void main(String[] args) {

        Class < ReflectionCreateObjects > clazz = ReflectionCreateObjects.class;

        Constructor < ReflectionCreateObjects > constructor;

        Constructor < ReflectionCreateObjects > constructor1;
        try {
            // Invoke No Args Constructor
            constructor = clazz.getConstructor();
            ReflectionCreateObjects obj = constructor.newInstance();
            System.out.println(obj);
            // Invoke Parameterized constructor
            constructor1 = clazz.getConstructor(String.class);
            ReflectionCreateObjects obj1 = constructor1.newInstance("testVar");
            System.out.println(obj1);
            // Use newInstance API of Class object
            ReflectionCreateObjects obj2 = clazz.newInstance();
            System.out.println(obj2);
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException |
            IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

}
ReflectionCreateObjects [var=null]
ReflectionCreateObjects [var=testVar]
ReflectionCreateObjects [var=null]

Related Article

Java Reflection : Interview questions

Leave a Reply

Your email address will not be published. Required fields are marked *