Java Dynamic Objects: Create Objects Dynamically With Reflection
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 known | At compile time | At runtime, often from a string |
| Errors found | By the compiler | As exceptions while running |
| Speed | Fastest | Slower, especially the first call |
| Typical use | Normal application code | Frameworks, 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,StringBuilderorHashMapas 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, andnewInstance()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 usegetDeclaredConstructor().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)matchesBatch(String, int)exactly.newInstance("Java Weekend", 30)boxes30to anInteger, and reflection unboxes it for theintparameter.- Looking up
Integer.classinstead ofint.classfails. 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 bygetParameterCount()orgetParameterTypes().
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:
| Exception | Cause in this example |
|---|---|
ClassNotFoundException | No class named com.example.Missing |
NoSuchMethodException | Runnable is an interface with no constructors; Integer has no no-arg constructor |
InstantiationException | Shape is abstract, so it cannot be instantiated |
IllegalAccessException | SecretKeyHolder's constructor is private |
InvocationTargetException | The 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:officialandextraare different objects. - Every enum has a hidden private constructor taking the constant's name and position. Even with
setAccessible(true),newInstancerefuses 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)returnsT, socreate(StringBuilder.class)gives aStringBuilderdirectly.asSubclass(Notifier.class)turnsClass<?>intoClass<? extends Notifier>. If the loaded class does not implementNotifier, it throwsClassCastExceptionbefore 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, socreateRecordworks 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-dimensionalint[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:
- Configuration. The text block plays the role of an
exporters.propertiesfile.Properties.loadturns eachkey=valueline into an entry, soexporter.csvmaps toCsvExporter. - Loading on demand.
forFormatreads the class name, loads it withClass.forNameand checks it withasSubclass(ReportExporter.class). Only formats that are actually requested get loaded. - Choosing a constructor. The loader first asks for a
(String)constructor and passes the report title.MarkdownExporterhas one;CsvExporterandJsonExporterdo not, so theNoSuchMethodExceptionsends the loader to the no-arg constructor. It usesgetDeclaredConstructor(), notgetConstructor(), because the compiler-generated default constructor has the same access as its class, and these classes are package-private, so their constructors are notpublic. - Caching. The second
csvrequest has no[loaded ...]line, because the exporter was reused from the map. - Bad configuration.
XmlExporterdoes not exist, soClassNotFoundExceptionis reported.java.lang.Stringexists but is not aReportExporter, soasSubclassthrowsClassCastExceptionbefore anything is created.docxhas no entry at all. - Adding a format. A new
HtmlExporterclass plus one lineexporter.html=HtmlExporterin the config is enough.ExporterRegistrynever changes. This open-for-extension design is exactly how JDBC drivers and logging back-ends are plugged in. The JDK'sServiceLoaderoffers 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.