Constructor.newInstance(): Creating Objects
What you'll learn: How to use Constructor.newInstance() to instantiate objects dynamically with arguments, matching parameters correctly and handling exceptions.
Creating Objects with Reflected Constructors
Once you've obtained a Constructor object via reflection, you call newInstance() to create an actual instance of the class. Unlike Class.newInstance() (deprecated), Constructor.newInstance() accepts arguments that match the constructor's parameter types.
Class<?> clazz = String.class;
Constructor<?> constructor = clazz.getConstructor(char[].class, int.class, int.class);
char[] chars = {'h', 'e', 'l', 'l', 'o'};
Object instance = constructor.newInstance(chars, 0, 5);
System.out.println(instance); // "hello"
Parameter Matching Rules
The arguments you pass to newInstance() must match the constructor's parameter types exactly (or be auto-boxable for primitives). If types mismatch, you'll get an IllegalArgumentException.
Constructor<?> intCtor = Integer.class.getConstructor(int.class);
Integer num = (Integer) intCtor.newInstance(42); // Works: autoboxing
// intCtor.newInstance("42"); // IllegalArgumentException: wrong type!
Handling InvocationTargetException
If the constructor itself throws an exception during execution, reflection wraps it in an InvocationTargetException. You must unwrap the cause to see the actual problem:
try {
Constructor<?> ctor = MyClass.getConstructor(int.class);
ctor.newInstance(-1); // Suppose constructor validates and throws IllegalArgumentException
} catch (InvocationTargetException e) {
Throwable actualCause = e.getCause(); // The real exception thrown by constructor
System.err.println("Constructor failed: " + actualCause.getMessage());
}
Key Takeaway: Use Constructor.newInstance(args...) to create objects dynamically, ensuring argument types match the constructor's parameters exactly and always catching InvocationTargetException to handle constructor-thrown exceptions properly.