Sub topic 4
Creating objects through constructors
Reflection lets you build an object without writing new for its class. This chapter covers how to find a constructor, call it, and handle the errors that come with it. It assumes you know what a Class object is, how to list members with getDeclaredConstructors(), and how checked exceptions work.
Why construct objects reflectively
You use new Point(3, 4) when the class is known at compile time. Reflection is for cases where the class name comes from configuration, a plugin list, or an annotation. Dependency-injection containers, serialization libraries, and test frameworks all create objects this way.
A Constructor<T> is a runtime object that represents one constructor of a class. Calling newInstance(...) on it runs that constructor and returns the new object.
Selecting a constructor
Constructors have no names, so you select one by its parameter types.
getConstructor(Class<?>... types)finds a public constructor.getDeclaredConstructor(Class<?>... types)finds a constructor of any access level, but only in that class.getConstructors()andgetDeclaredConstructors()return arrays. The order of the elements is not specified, so never rely on it.
Constructors are not inherited. Asking a subclass for a superclass constructor fails.
import java.lang.reflect.Constructor;
class Point {
private final int x;
private final int y;
public Point() {
this(0, 0);
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
private Point(String text) {
String[] parts = text.split(",");
this.x = Integer.parseInt(parts[0].trim());
this.y = Integer.parseInt(parts[1].trim());
}
@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}
}
public class CtorDemo {
public static void main(String[] args) throws Exception {
Point origin = Point.class.getConstructor().newInstance();
Constructor<Point> twoInts = Point.class.getConstructor(int.class, int.class);
Point p = twoInts.newInstance(3, 4);
Constructor<Point> parser = Point.class.getDeclaredConstructor(String.class);
parser.setAccessible(true);
Point q = parser.newInstance("7, 8");
System.out.println(origin);
System.out.println(p);
System.out.println(q);
try {
Point.class.getConstructor(String.class);
} catch (NoSuchMethodException e) {
System.out.println("no public constructor taking a String");
}
try {
Point.class.getConstructor(Integer.class, Integer.class);
} catch (NoSuchMethodException e) {
System.out.println("Integer is not int");
}
}
}The program prints the three points, then the two messages.
The parameter types must match exactly. A constructor declared with int is found with int.class, not Integer.class. The second catch block above shows this failure. When you call newInstance, the arguments are Objects, so 3 and 4 are boxed automatically and then unwrapped to match the int parameters.
The newInstance contract
Constructor.newInstance(Object... initargs) does the following:
- It checks that the caller may access the constructor, unless
setAccessible(true)succeeded. - It checks the argument count and types, with boxing and unboxing and widening conversions such as
inttolong. - It runs the constructor, including field initializers and any
super(...)call. - It returns the new object as
T. No cast is needed when you have aConstructor<Point>.
A constructor whose last parameter is varargs has an array type, for example String[].class. Pass the array as one argument and cast it to Object, as in ctor.newInstance((Object) names). Without the cast, the compiler spreads the array into separate arguments and the call fails with IllegalArgumentException.
Avoid Class.newInstance(). It has been deprecated since Java 9. It can throw checked exceptions from the constructor without declaring them. It also works only with a no-argument constructor that is visible to the caller. getDeclaredConstructor().newInstance() has none of these problems.
What can go wrong
Each failure has its own exception type. Learn to tell them apart, because the cause of the problem differs.
| Exception | Meaning |
|---|---|
| `NoSuchMethodException` | No constructor has those parameter types. This is thrown when selecting, not when calling. |
| `IllegalAccessException` | The constructor, or its class, is not accessible to the caller. |
| `InstantiationException` | The class is abstract, an interface, an array class, or a primitive type. |
| `IllegalArgumentException` | The number or types of the arguments do not match. |
| `InvocationTargetException` | The constructor itself threw an exception. The real error is in `getCause()`. |
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
abstract class Shape {
}
class Circle extends Shape {
Circle(double radius) {
if (radius <= 0) {
throw new IllegalArgumentException("radius must be positive");
}
}
}
public class CtorErrors {
public static void main(String[] args) throws Exception {
try {
Shape.class.getDeclaredConstructor().newInstance();
} catch (InstantiationException e) {
System.out.println("abstract class: " + e);
}
Constructor<Circle> ctor = Circle.class.getDeclaredConstructor(double.class);
try {
ctor.newInstance("big");
} catch (IllegalArgumentException e) {
System.out.println("bad argument: " + e.getMessage());
}
try {
ctor.newInstance(-1.0);
} catch (InvocationTargetException e) {
System.out.println("constructor threw: " + e.getCause());
}
}
}In the last case, IllegalArgumentException is the constructor's own exception. It arrives wrapped in InvocationTargetException, so the catch for plain IllegalArgumentException above it does not intercept it. The wrapping is what separates "reflection was misused" from "the target code failed".
A small factory by class name
A common use is building an object from a class name and arguments. The helper below tries each public constructor and calls the first one whose parameters accept the arguments. It maps primitive parameter types to their wrappers, because Class.isInstance never returns true for a primitive class.
import java.lang.reflect.Constructor;
import java.util.Map;
public class Factory {
private static final Map<Class<?>, Class<?>> WRAPPERS = Map.of(
int.class, Integer.class,
long.class, Long.class,
double.class, Double.class,
boolean.class, Boolean.class);
static Object create(String className, Object... args) throws Exception {
Class<?> type = Class.forName(className);
for (Constructor<?> c : type.getConstructors()) {
if (accepts(c.getParameterTypes(), args)) {
return c.newInstance(args);
}
}
throw new NoSuchMethodException(
"no public constructor of " + className + " accepts these arguments");
}
private static boolean accepts(Class<?>[] params, Object[] args) {
if (params.length != args.length) {
return false;
}
for (int i = 0; i < params.length; i++) {
if (args[i] == null) {
if (params[i].isPrimitive()) {
return false;
}
continue;
}
Class<?> expected = WRAPPERS.getOrDefault(params[i], params[i]);
if (!expected.isInstance(args[i])) {
return false;
}
}
return true;
}
public static void main(String[] args) throws Exception {
System.out.println(create("java.lang.StringBuilder", "abc"));
System.out.println(create("java.util.ArrayList", 10));
}
}The output is abc and []. Two constructors of StringBuilder accept a String, namely String and CharSequence. Since getConstructors() has no defined order, the helper may pick either one. Both give the same result here. A real framework needs a rule for ambiguity, such as choosing the most specific match or failing with an error.
Special cases
- Inner classes. A non-static inner class constructor takes the enclosing instance as a hidden first parameter. To reach
Outer.Inner(String), ask forgetDeclaredConstructor(Outer.class, String.class)and pass anOuterobject first. A static nested class has no such parameter. - Arrays. Arrays have no constructors. Use
java.lang.reflect.Array.newInstance(String.class, 5)to create aString[5]. - Enums.
newInstancerefuses to build enum constants and throwsIllegalArgumentException. Look up constants withgetEnumConstants()orEnum.valueOf. - Non-public classes. A public constructor in a package-private class is still inaccessible from other packages. Calling
setAccessible(true)on the constructor fixes this in most cases. - No-argument constructors. Many libraries require one, and the compiler provides it only when you write no constructor at all. If you add a parameterized constructor, add a no-argument one too.
Design notes
Constructor lookup costs time, so frameworks look a Constructor up once and cache it. Skipping new also skips compile-time checking: a renamed parameter type becomes a runtime NoSuchMethodException. Prefer new, a factory interface, or ServiceLoader when you control the code. Use reflective construction when the class genuinely cannot be known until runtime.
Exercise
A class Report has a public constructor Report(long id). The call Report.class.getConstructor(Long.class) throws NoSuchMethodException. Why does it fail, how do you fix it, and which exception do you expect if the constructor body throws IllegalStateException?
Show answer
The parameter is the primitive long, and Long.class is a different Class object, so the types do not match. Use Report.class.getConstructor(long.class), then call newInstance(42L) (boxing happens automatically). If the constructor body throws IllegalStateException, newInstance throws InvocationTargetException, and the IllegalStateException is available from getCause().
Exercise
You call getDeclaredConstructor().newInstance() on an interface type and get an exception. Which one is it, and why does getDeclaredConstructor() itself not fail with a different one first?
Show answer
Interfaces have no constructors, so getDeclaredConstructor() throws NoSuchMethodException before newInstance is reached. InstantiationException is the one you meet for abstract classes. Those do have a constructor to look up, but cannot be instantiated.