We can instantiate a class via Constructor.newInstance() using the Java Reflection API.
Let's consider the following class, which has four constructors:
public class Car {
private int id;
private String name;
private Color color;
public Car() {}
public Car(int id, String name) {
this.id = id;
this.name = name;
}
public Car(int id, Color color) {
this.id = id;
this.color = color;
}
public Car(int id, String name, Color color) {
this.id = id;
this.name = name;
this.color = color;
}
// getters and setters omitted for brevity
}
A Car instance can be created via one of these four constructors. The Constructor class exposes a method that takes the types of the parameters of a constructor and returns a Constructor object that reflects the matched constructor. This method is called getConstructor​(Class<?>... parameterTypes).
Let's call each of the preceding constructors:
Class<Car> clazz = Car.class;
Constructor<Car> emptyCnstr
= clazz.getConstructor();
Constructor<Car> idNameCnstr
= clazz.getConstructor(int.class, String.class);
Constructor<Car> idColorCnstr
= clazz.getConstructor(int.class, Color.class);
Constructor<Car> idNameColorCnstr
= clazz.getConstructor(int.class, String.class, Color.class);
Furthermore, Constructor.newInstance​(Object... initargs) can return an instance of Car that corresponds with the invoked constructor:
Car carViaEmptyCnstr = emptyCnstr.newInstance();
Car carViaIdNameCnstr = idNameCnstr.newInstance(1, "Dacia");
Car carViaIdColorCnstr = idColorCnstr
.newInstance(1, new Color(0, 0, 0));
Car carViaIdNameColorCnstr = idNameColorCnstr
.newInstance(1, "Dacia", new Color(0, 0, 0));
Now, is time to see how we can instantiate a private constructor via reflection.