Sub topic 4
Creating objects through constructors
This chapter assumes you know how to find a Class object and list its members, as covered in the earlier chapters. It also assumes you are comfortable with checked exceptions.
Why create objects reflectively
Normally you write new Person("Ada"), so the class is fixed when you compile. Sometimes the class name is only known at runtime, for example when it comes from a configuration file or a plugin list. In that case you ask the Class object for a Constructor and call it. Frameworks use this to build objects you never wrote new for.
Finding a constructor
A Constructor<T> object represents one constructor. You pick it by its parameter types, in order.
getConstructor(Class<?>... types)finds a public constructor.getDeclaredConstructor(Class<?>... types)finds any constructor declared in that class, including private ones.getConstructors()andgetDeclaredConstructors()return arrays of all of them.
Constructors are not inherited, so these methods only see the class you asked about. Primitive parameters use primitive class literals: use int.class, not Integer.class.
Calling the constructor
Constructor.newInstance(Object... args) runs the constructor and returns the new object. The arguments must match the parameter types. Primitive arguments are boxed for you.
import java.lang.reflect.Constructor;
class Person {
private final String name;
private final int age;
public Person(String name) {
this(name, 0);
}
private Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" + name + ", " + age + "}";
}
}
public class CtorDemo {
public static void main(String[] args) throws Exception {
Constructor<Person> publicCtor = Person.class.getConstructor(String.class);
Person a = publicCtor.newInstance("Ada");
System.out.println(a);
Constructor<Person> privateCtor =
Person.class.getDeclaredConstructor(String.class, int.class);
privateCtor.setAccessible(true);
Person b = privateCtor.newInstance("Grace", 45);
System.out.println(b);
}
}This prints Person{Ada, 0} and then Person{Grace, 45}. The private constructor only works after setAccessible(true). The next chapter on access checks covers what that call does and where modules restrict it.
The no-argument shortcut
When a class has a no-argument constructor, the idiomatic call is type.getDeclaredConstructor().newInstance(). You may see Class.newInstance() in older code. It has been deprecated since Java 9 because it can throw checked exceptions without declaring them.
What can go wrong
| Exception | Typical cause |
|---|---|
| `NoSuchMethodException` | No constructor matches the parameter types you passed to `getConstructor`. |
| `IllegalAccessException` | The constructor is not accessible and you did not call `setAccessible(true)`. |
| `InstantiationException` | The class is abstract or an interface. |
| `InvocationTargetException` | The constructor ran and threw an exception. |
| `IllegalArgumentException` | The number or types of arguments passed to `newInstance` do not match. |
A common mistake is passing Integer.class when the constructor takes int. That produces NoSuchMethodException, because the two types differ.
Choosing a constructor at runtime
Exercise
A class Config has only a public constructor Config(int retries). Your code calls Config.class.getConstructor(Integer.class). What happens, and how do you fix it?
Show answer
It throws NoSuchMethodException, because the constructor's parameter type is the primitive int, not Integer. Use Config.class.getConstructor(int.class), then call newInstance(3). The argument 3 is boxed automatically.