September 2019
Intermediate to advanced
816 pages
18h 47m
English
The Java Reflection API can be used to instantiate a class via its private constructor as well. For example, let's suppose that we have a utility class called Cars. Following best practices, we will define this class as final and with a private constructor to not allow instances:
public final class Cars { private Cars() {} // static members}
Fetching this constructor can be accomplished via Class.getDeclaredConstructor(), as follows:
Class<Cars> carsClass = Cars.class;Constructor<Cars> emptyCarsCnstr = carsClass.getDeclaredConstructor();
Calling newInstance() at this instance will throw IllegalAccessException since the invoked constructor has private access. However, Java Reflection allows us ...