A2oz

How Can We Create an Object Dynamically at Runtime in Java?

Published in Java Programming 2 mins read

You can create objects dynamically at runtime in Java using reflection. Reflection allows you to access and manipulate classes and objects at runtime, including creating new instances of classes.

Here's a breakdown of how to achieve this:

1. Using Class.forName() and newInstance()

  • The Class.forName() method takes the fully qualified name of a class as a string and returns a Class object representing that class.
  • The newInstance() method of the Class object creates a new instance of the class.
Class<?> myClass = Class.forName("com.example.MyClass");
Object myObject = myClass.newInstance();

2. Using Constructor.newInstance()

  • You can obtain a Constructor object using the getConstructor() method of the Class object.
  • The newInstance() method of the Constructor object creates a new instance of the class using the specified constructor.
Class<?> myClass = Class.forName("com.example.MyClass");
Constructor<?> constructor = myClass.getConstructor(String.class, int.class);
Object myObject = constructor.newInstance("John", 25);

3. Using Class.getDeclaredConstructor() and newInstance()

  • Use getDeclaredConstructor() to access private constructors.
  • This allows you to create instances of classes with private constructors, which are otherwise inaccessible.
Class<?> myClass = Class.forName("com.example.MyClass");
Constructor<?> constructor = myClass.getDeclaredConstructor(String.class);
constructor.setAccessible(true);
Object myObject = constructor.newInstance("Jane");

Practical Insights:

  • Dynamic object creation is useful for scenarios where you need to create objects based on user input or configuration files.
  • Reflection can be used to create instances of classes that are not known at compile time.
  • Be mindful of the potential performance overhead associated with reflection.

Example:

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

public class DynamicObjectCreation {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        // Get the class name from the user
        String className = "com.example.MyClass";

        // Create an instance of the class dynamically
        Class<?> myClass = Class.forName(className);
        Constructor<?> constructor = myClass.getConstructor(String.class);
        Object myObject = constructor.newInstance("John");

        // Use the created object
        System.out.println(myObject.toString());
    }
}

Related Articles