Instantiating a class via a private constructor

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 to modify the access level via the flag method, Constructor.setAccessible(). This time, the instantiation works as expected:

emptyCarsCnstr.setAccessible(true);
Cars carsViaEmptyCnstr = emptyCarsCnstr.newInstance();

In order to block this approach, it is advisable to throw an error from a private constructor, as follows:

public final class Cars {

private Cars() {
throw new AssertionError("Cannot be instantiated");
}

// static members
}

This time, the instantiation attempt will fail with AssertionError.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.122.127