CKTIS / Java
Creating objects reflectively with Constructor.newInstance
Invoke a specific constructor in Java SE 21 and distinguish lookup or invocation failures from exceptions thrown by the constructor itself.
Version: Java SE 21
Syntax
public T newInstance(Object... initargs)
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetExceptionConstructor.newInstance in java.lang.reflect invokes the constructor represented by a Constructor<T> object and returns a fresh instance of type T. First select the constructor by its exact formal parameter types, in declaration order. getConstructor(...) looks up public constructors only; getDeclaredConstructor(...) also finds non-public ones, but finding one does not grant access to invoke it. No matching constructor means NoSuchMethodException at lookup time.
At invocation, pass values rather than Class objects describing their types. No overload is selected again. Reflection can unbox wrapper values and apply primitive widening, but not narrowing. For a zero-parameter constructor, call ctor.newInstance(). For an array parameter, including a constructor's varargs parameter, pass a ready-made array as one argument; casting a reference array to (Object) keeps it from becoming newInstance's entire argument list. For a non-static member class, the enclosing instance is the first argument.
If access checks are in force, an inaccessible constructor causes IllegalAccessException. trySetAccessible() can return false when module rules prevent suppressing those checks. A wrong argument count, an incompatible argument, or an attempt to instantiate an enum causes IllegalArgumentException; an abstract class causes InstantiationException. If invocation triggers class initialization and that initialization fails, ExceptionInInitializerError can occur.
If the constructor itself throws an exception, reflection wraps it in the checked InvocationTargetException; use getCause() to inspect the original failure. This distinguishes an exception inside the constructor from a call rejected by reflection. The deprecated Class.newInstance() can invoke only a zero-argument constructor and propagates its exception without that wrapper.
Examples
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ConstructorDemo {
public static void main(String[] args) throws ReflectiveOperationException {
Constructor<StringBuilder> fromText =
StringBuilder.class.getConstructor(String.class);
StringBuilder builder = fromText.newInstance("Java");
System.out.println(builder.append(" 21"));
Constructor<StringBuilder> fromCapacity =
StringBuilder.class.getConstructor(int.class);
try {
fromCapacity.newInstance(-1);
throw new AssertionError("Expected a negative capacity to fail");
} catch (InvocationTargetException e) {
System.out.println(e.getCause().getClass().getSimpleName());
}
}
}Result
Java 21 NegativeArraySizeException
`StringBuilder(String)` creates a builder to which the program appends `" 21"`. Then `StringBuilder(int)` rejects the capacity `-1`: the `catch` block catches `InvocationTargetException` and prints the original cause's type name. Other checked reflection failures propagate.
Related lessons
- Java · Lesson 13 · Advanced · Version: 2
Sources
- Java SE 21 API — Constructor.newInstance(Object...)
- Java SE 21 API — Class.getConstructor(Class<?>...)
- Java SE 21 API — Class.getDeclaredConstructor(Class<?>...)
- Java SE 21 API — AccessibleObject.trySetAccessible()
- Java SE 21 API — InvocationTargetException.getCause()
- Java SE 21 API — StringBuilder(String)
- Java SE 21 API — StringBuilder(int)
- Java SE 21 API — Class.newInstance() (deprecated)