Java Dynamic Objects: Create Objects Dynamically With Reflection

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 239 of 306

Java dynamic objects are objects whose class is chosen while the program runs, not when it is compiled. Instead of writing new CsvExporter(), you read a class name such as "CsvExporter" from a config file and let reflection create the object. This is how you create objects dynamically in Java.

Plugin systems, dependency injection containers, JDBC drivers and test frameworks all work this way. This lesson builds on Java Reflection API and Java Class Metadata: it shows every way to create objects at runtime, the errors you must handle, and ends with a configurable plugin loader.


Java Dynamic Objects vs the new Keyword

new Type(...)Reflection
Class knownAt compile timeAt runtime, often from a string
Errors foundBy the compilerAs exceptions while running
SpeedFastestSlower, especially the first call
Typical useNormal application codeFrameworks, plugins, configuration-driven code

The reflective path has two steps: get a Constructor from the Class, then call newInstance on it.

Class<?> type = Class.forName("fully.qualified.ClassName");
Object instance = type.getDeclaredConstructor().newInstance();

Creating an Object From a Class Name

The simplest case uses a public no-argument constructor:

import java.util.List;

public class CreateByName {
    public static void main(String[] args) throws ReflectiveOperationException {
        List<String> classNames = List.of("java.util.ArrayList", "java.lang.StringBuilder", "java.util.HashMap");

        for (String className : classNames) {
            Class<?> type = Class.forName(className);                       // 1. load the class
            Object instance = type.getDeclaredConstructor().newInstance();  // 2. call its no-arg constructor
            System.out.println(className + " -> " + instance.getClass().getSimpleName() + " value=" + instance);
        }
    }
}

Output:

java.util.ArrayList -> ArrayList value=[]
java.lang.StringBuilder -> StringBuilder value=
java.util.HashMap -> HashMap value={}

How it works:

  • The program never mentions ArrayList, StringBuilder or HashMap as types. The class names are plain strings, so they could just as well come from a file or a database.
  • getDeclaredConstructor() with no arguments finds the no-arg constructor, and newInstance() runs it.
  • The variable type is Object, because the compiler cannot know which class will be created.

Note: Class.newInstance() is deprecated since Java 9. It could throw checked exceptions without declaring them. Always use getDeclaredConstructor().newInstance() instead.


Calling Constructors With Arguments

To pass arguments, look up the constructor by its exact parameter types. Primitive parameters must be described with primitive class literals such as int.class.

import java.lang.reflect.Constructor;
import java.util.Arrays;

class Batch {
    private final String name;
    private final int capacity;

    public Batch(String name) {
        this(name, 25);
    }

    public Batch(String name, int capacity) {
        this.name = name;
        this.capacity = capacity;
    }

    @Override
    public String toString() {
        return name + " (" + capacity + " seats)";
    }
}

public class ConstructorArgs {
    public static void main(String[] args) throws ReflectiveOperationException {
        Class<?> type = Class.forName("Batch");

        Constructor<?> twoArgs = type.getConstructor(String.class, int.class);
        System.out.println("Created: " + twoArgs.newInstance("Java Weekend", 30));

        Constructor<?> oneArg = type.getConstructor(String.class);
        System.out.println("Created: " + oneArg.newInstance("Java Evening"));

        try {
            type.getConstructor(String.class, Integer.class); // wrapper instead of primitive
        } catch (NoSuchMethodException e) {
            System.out.println("Not found: " + e.getMessage());
        }

        for (Constructor<?> constructor : type.getConstructors()) {
            if (constructor.getParameterCount() == 2) {
                System.out.println("Two-arg parameter types: " + Arrays.toString(constructor.getParameterTypes()));
            }
        }
    }
}

Output:

Created: Java Weekend (30 seats)
Created: Java Evening (25 seats)
Not found: Batch.<init>(java.lang.String,java.lang.Integer)
Two-arg parameter types: [class java.lang.String, int]

How it works:

  • getConstructor(String.class, int.class) matches Batch(String, int) exactly. newInstance("Java Weekend", 30) boxes 30 to an Integer, and reflection unboxes it for the int parameter.
  • Looking up Integer.class instead of int.class fails. Constructor lookup does not apply boxing; <init> in the message is the JVM's name for a constructor.
  • When you do not know the exact types, loop over getConstructors() and choose by getParameterCount() or getParameterTypes().

Errors When Creating Objects Dynamically

Dynamic creation moves many compile-time errors to runtime. This example triggers each one on purpose:

import java.lang.reflect.InvocationTargetException;
import java.util.List;

abstract class Shape {
    public Shape() { }
}

class SecretKeyHolder {
    private SecretKeyHolder() { }
}

class FailingService {
    public FailingService() {
        throw new IllegalStateException("config file missing");
    }
}

public class CreationErrors {

    static String tryCreate(String className) {
        try {
            Object created = Class.forName(className).getDeclaredConstructor().newInstance();
            return "OK, created " + created.getClass().getSimpleName();
        } catch (InvocationTargetException e) {
            return "InvocationTargetException caused by " + e.getCause();
        } catch (ReflectiveOperationException e) {
            return e.getClass().getSimpleName();
        }
    }

    public static void main(String[] args) {
        List<String> classNames = List.of("java.util.ArrayList", "com.example.Missing", "java.lang.Runnable",
                "java.lang.Integer", "Shape", "SecretKeyHolder", "FailingService");
        for (String className : classNames) {
            System.out.printf("%-20s -> %s%n", className, tryCreate(className));
        }
    }
}

Output:

java.util.ArrayList  -> OK, created ArrayList
com.example.Missing  -> ClassNotFoundException
java.lang.Runnable   -> NoSuchMethodException
java.lang.Integer    -> NoSuchMethodException
Shape                -> InstantiationException
SecretKeyHolder      -> IllegalAccessException
FailingService       -> InvocationTargetException caused by java.lang.IllegalStateException: config file missing

How it works:

ExceptionCause in this example
ClassNotFoundExceptionNo class named com.example.Missing
NoSuchMethodExceptionRunnable is an interface with no constructors; Integer has no no-arg constructor
InstantiationExceptionShape is abstract, so it cannot be instantiated
IllegalAccessExceptionSecretKeyHolder's constructor is private
InvocationTargetExceptionThe constructor ran and threw; the real error is in getCause()

All of them extend ReflectiveOperationException, so one catch handles the general case. Catch InvocationTargetException first when you want to report the real cause.


Private Constructors and Enum Restrictions

setAccessible(true) lets reflection call a private constructor in your own code. Enums are the one type the JVM refuses to create reflectively, which is what makes enum singletons safe.

import java.lang.reflect.Constructor;

class AppConfig {
    private static final AppConfig INSTANCE = new AppConfig();

    private AppConfig() {
        System.out.println("AppConfig constructor ran");
    }

    static AppConfig getInstance() {
        return INSTANCE;
    }
}

enum Plan { FREE, PRO }

public class PrivateConstructors {
    public static void main(String[] args) throws ReflectiveOperationException {
        AppConfig official = AppConfig.getInstance();

        Constructor<AppConfig> hidden = AppConfig.class.getDeclaredConstructor();
        hidden.setAccessible(true);
        AppConfig extra = hidden.newInstance();
        System.out.println("Same object? " + (official == extra));

        Constructor<Plan> enumConstructor = Plan.class.getDeclaredConstructor(String.class, int.class);
        enumConstructor.setAccessible(true);
        try {
            enumConstructor.newInstance("ENTERPRISE", 2);
        } catch (IllegalArgumentException e) {
            System.out.println("Enum: " + e.getMessage());
        }
    }
}

Output:

AppConfig constructor ran
AppConfig constructor ran
Same object? false
Enum: Cannot reflectively create enum objects

How it works:

  • The first line comes from creating INSTANCE. The second comes from reflection calling the private constructor again, which breaks the singleton: official and extra are different objects.
  • Every enum has a hidden private constructor taking the constant's name and position. Even with setAccessible(true), newInstance refuses to run it, so no extra enum constant can ever exist.

A Type-Safe Generic Factory

Returning Object forces casts everywhere. A generic factory method uses Class<T> to return the right type, and asSubclass checks that a class loaded by name really implements the expected interface.

interface Notifier {
    String send(String message);
}

class EmailNotifier implements Notifier {
    public String send(String message) {
        return "Email sent: " + message;
    }
}

class Factory {

    static <T> T create(Class<T> type) throws ReflectiveOperationException {
        return type.getDeclaredConstructor().newInstance();
    }

    static <T> T create(String className, Class<T> expectedType) throws ReflectiveOperationException {
        Class<? extends T> type = Class.forName(className).asSubclass(expectedType);
        return type.getDeclaredConstructor().newInstance();
    }
}

public class TypeSafeFactory {
    public static void main(String[] args) throws ReflectiveOperationException {
        StringBuilder builder = Factory.create(StringBuilder.class); // no cast needed
        builder.append("typed result");
        System.out.println(builder);

        Notifier notifier = Factory.create("EmailNotifier", Notifier.class);
        System.out.println(notifier.send("Welcome to GOCOURSE"));

        try {
            Factory.create("java.util.ArrayList", Notifier.class);
        } catch (ClassCastException e) {
            System.out.println("Rejected: " + e.getMessage() + " is not a Notifier");
        }

        Object unknown = Factory.create("EmailNotifier", Object.class);
        Notifier checked = Notifier.class.cast(unknown); // runtime-checked cast
        System.out.println(checked.send("cast works"));
    }
}

Output:

typed result
Email sent: Welcome to GOCOURSE
Rejected: class java.util.ArrayList is not a Notifier
Email sent: cast works

How it works:

  • create(Class<T> type) returns T, so create(StringBuilder.class) gives a StringBuilder directly.
  • asSubclass(Notifier.class) turns Class<?> into Class<? extends Notifier>. If the loaded class does not implement Notifier, it throws ClassCastException before any object is created.
  • Notifier.class.cast(object) is the reflective form of (Notifier) object, useful inside generic code where the target type is a variable.

Creating Records, Enums and Arrays Dynamically

Records, enums and arrays each have their own dynamic creation path.

import java.lang.reflect.Array;
import java.lang.reflect.RecordComponent;
import java.util.Arrays;

record Coupon(String code, int percent) { }

enum Level { BEGINNER, INTERMEDIATE, ADVANCED }

public class RecordsEnumsArrays {

    static <T extends Record> T createRecord(Class<T> type, Object... values) throws ReflectiveOperationException {
        Class<?>[] componentTypes = Arrays.stream(type.getRecordComponents())
                .map(RecordComponent::getType)
                .toArray(Class<?>[]::new);
        return type.getDeclaredConstructor(componentTypes).newInstance(values); // canonical constructor
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        Coupon coupon = createRecord(Coupon.class, "DIWALI25", 25);
        System.out.println(coupon);

        Level level = Enum.valueOf(Level.class, "INTERMEDIATE");
        System.out.println(level + " has ordinal " + level.ordinal());

        int[][] seatGrid = (int[][]) Array.newInstance(int.class, 2, 3);
        seatGrid[1][2] = 7;
        System.out.println(Arrays.deepToString(seatGrid));

        String[] names = (String[]) Array.newInstance(String.class, 2);
        System.out.println(names.getClass().getSimpleName() + " of length " + names.length);
    }
}

Output:

Coupon[code=DIWALI25, percent=25]
INTERMEDIATE has ordinal 1
[[0, 0, 0], [0, 0, 7]]
String[] of length 2

How it works:

  • Every record has a canonical constructor whose parameters match its components in order. getRecordComponents() provides those types, so createRecord works for any record.
  • Enums are never constructed; you look up an existing constant by name with Enum.valueOf(Class, String).
  • Array.newInstance(int.class, 2, 3) creates a two-dimensional int[2][3]. The extra size arguments add dimensions.

Real-World Example: A Configurable Plugin Loader

Reporting tools often support many output formats, and new formats should not require changing the core code. This example reads format=ClassName pairs from a properties file, loads each exporter class on demand, checks its type, picks the right constructor and caches the result.

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringJoiner;

// ---------- the plugin contract ----------
interface ReportExporter {
    String export(List<String[]> rows);
}

// ---------- three plugins ----------
class CsvExporter implements ReportExporter {
    public String export(List<String[]> rows) {
        StringJoiner out = new StringJoiner("\n");
        for (String[] row : rows) {
            out.add(String.join(",", row));
        }
        return out.toString();
    }
}

class JsonExporter implements ReportExporter {
    public String export(List<String[]> rows) {
        StringJoiner out = new StringJoiner(", ", "[", "]");
        for (String[] row : rows) {
            out.add("{\"student\": \"" + row[0] + "\", \"score\": " + row[1] + "}");
        }
        return out.toString();
    }
}

class MarkdownExporter implements ReportExporter {
    private final String title;

    public MarkdownExporter(String title) { // this plugin needs a title
        this.title = title;
    }

    public String export(List<String[]> rows) {
        StringBuilder out = new StringBuilder("## " + title + "\n| Student | Score |\n|---|---|");
        for (String[] row : rows) {
            out.append("\n| ").append(row[0]).append(" | ").append(row[1]).append(" |");
        }
        return out.toString();
    }
}

// ---------- the loader ----------
class ExporterRegistry {
    private final Properties config;
    private final String reportTitle;
    private final Map<String, ReportExporter> cache = new HashMap<>();

    ExporterRegistry(Properties config, String reportTitle) {
        this.config = config;
        this.reportTitle = reportTitle;
    }

    ReportExporter forFormat(String format) throws ReflectiveOperationException {
        ReportExporter cached = cache.get(format);
        if (cached != null) {
            return cached;
        }

        String className = config.getProperty("exporter." + format);
        if (className == null) {
            throw new IllegalArgumentException("No exporter configured for '" + format + "'");
        }

        Class<? extends ReportExporter> type = Class.forName(className).asSubclass(ReportExporter.class);
        ReportExporter exporter;
        try {
            Constructor<? extends ReportExporter> withTitle = type.getConstructor(String.class);
            exporter = withTitle.newInstance(reportTitle);       // prefer the title constructor
        } catch (NoSuchMethodException noTitleConstructor) {
            exporter = type.getDeclaredConstructor().newInstance(); // fall back to no-arg
        }

        cache.put(format, exporter);
        System.out.println("[loaded " + type.getSimpleName() + " for '" + format + "']");
        return exporter;
    }
}

public class ExportPlugins {
    public static void main(String[] args) throws IOException {
        String configText = """
                exporter.csv=CsvExporter
                exporter.json=JsonExporter
                exporter.md=MarkdownExporter
                exporter.xml=XmlExporter
                exporter.pdf=java.lang.String
                """;
        Properties config = new Properties();
        config.load(new StringReader(configText));

        ExporterRegistry registry = new ExporterRegistry(config, "Java Batch 7 Results");
        List<String[]> rows = List.of(new String[] {"Asha", "92"}, new String[] {"Ravi", "78"});

        for (String format : List.of("csv", "json", "md", "csv", "xml", "pdf", "docx")) {
            System.out.println("== " + format);
            try {
                System.out.println(registry.forFormat(format).export(rows));
            } catch (ClassNotFoundException e) {
                System.out.println("Plugin class not found: " + e.getMessage());
            } catch (ClassCastException e) {
                System.out.println("Not a ReportExporter: " + e.getMessage());
            } catch (ReflectiveOperationException | IllegalArgumentException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
}

Output:

== csv
[loaded CsvExporter for 'csv']
Asha,92
Ravi,78
== json
[loaded JsonExporter for 'json']
[{"student": "Asha", "score": 92}, {"student": "Ravi", "score": 78}]
== md
[loaded MarkdownExporter for 'md']
## Java Batch 7 Results
| Student | Score |
|---|---|
| Asha | 92 |
| Ravi | 78 |
== csv
Asha,92
Ravi,78
== xml
Plugin class not found: XmlExporter
== pdf
Not a ReportExporter: class java.lang.String
== docx
Error: No exporter configured for 'docx'

How it works:

  1. Configuration. The text block plays the role of an exporters.properties file. Properties.load turns each key=value line into an entry, so exporter.csv maps to CsvExporter.
  2. Loading on demand. forFormat reads the class name, loads it with Class.forName and checks it with asSubclass(ReportExporter.class). Only formats that are actually requested get loaded.
  3. Choosing a constructor. The loader first asks for a (String) constructor and passes the report title. MarkdownExporter has one; CsvExporter and JsonExporter do not, so the NoSuchMethodException sends the loader to the no-arg constructor. It uses getDeclaredConstructor(), not getConstructor(), because the compiler-generated default constructor has the same access as its class, and these classes are package-private, so their constructors are not public.
  4. Caching. The second csv request has no [loaded ...] line, because the exporter was reused from the map.
  5. Bad configuration. XmlExporter does not exist, so ClassNotFoundException is reported. java.lang.String exists but is not a ReportExporter, so asSubclass throws ClassCastException before anything is created. docx has no entry at all.
  6. Adding a format. A new HtmlExporter class plus one line exporter.html=HtmlExporter in the config is enough. ExporterRegistry never changes. This open-for-extension design is exactly how JDBC drivers and logging back-ends are plugged in. The JDK's ServiceLoader offers the same idea with automatic discovery.

The next lesson, Java Dynamic Proxy, goes one step further: instead of creating objects of existing classes, it generates brand-new classes at runtime that intercept every method call.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Dynamic Objects: Create Objects Dynamically With Reflection and get answers drawn from it.

Signed-in readers only.