Why java.util.Objects private constructor throws assertionError

I noticed that java.util.Objects has a constructor that throws an AssertionError.

* @since 1.7 */ public final class Objects { private Objects() { throw new AssertionError("No java.util.Objects instances for you!"); } ... 

This is a static utility class and therefore no instance is required.

One of the possible reasons why I understand that the developer is trying to make sure that an instance of this class is not created. As the only way anyone can call this constructor is reflection.

Is there any other reason to create such a constructor?

+6
source share
2 answers

The only goal is to ensure non-investment. Since it is private , AssertionError is mainly for reflection and for the class itself, because private constructors can be called from the class itself. And as a side effect, this idiom also prevents a subclass of the class.

Quote from Effective Java 2nd Edition Point 4:

 // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } ... // Remainder omitted } 

Since the explicit constructor is private, it is not available outside the class. AssertionError is not strictly required, but it provides insurance in case the constructor is accidentally called from the class. It guarantees that a class will never be created under any circumstances. This idiom is slightly counterintuitive as the constructor is provided explicitly so that it cannot be called. Therefore, it is advisable to include a comment as shown above. As a side effect, this idiom also prevents a subclass of the class. All constructors must reference the constructor of the superclass, explicitly or implicitly, and the subclass will not have an available superclass constructor to call.

You may also find this question helpful:

What is preferable Throwable for use in the constructor of a private class?

+11
source

They simply created this private constructor to ensure that no one can instantiate this class. And to prevent instantiation using reflection, an error occurs. Therefore, I think your understanding of this design is correct;)

0
source

Source: https://habr.com/ru/post/974797/


All Articles