Article 4 of "Effective Java" strengthens the ability to not instantiate through private constructs

This article is mainly for some tool classes, such as java.lang.Math, , java.util.Arrays, java.util.Collenctionsetc. The methods in these classes are all static methods. The designer does not want these classes to be instantiated, mainly because instantiating these classes has no meaning.

At this time, you can strengthen the non-instantiability capability by setting the constructor to private. For example, Collectionsthe constructor in the class is as follows:

    // Suppresses default constructor, ensuring non-instantiability.
    private Collections() {
    
    
    }

Private construction guarantees the following two things:

(1) It is impossible to create an instance through direct new.

(2) Its subclasses cannot be instantiated because they cannot explicitly or implicitly call the constructor of the parent class.

Of course, this only enhances the ability to be non-instantiable. In fact, instances can still be created through reflection or deserialization. For example, the Collectionsinstance is created through reflection as follows:

        List<Integer> list = Stream.of(1, 3, 2, 44, 34).collect(Collectors.toList());
        Class<Collections> collectionsClass = Collections.class;
        Constructor<Collections> constructor = collectionsClass.getDeclaredConstructor(null);
        constructor.setAccessible(true);
        Collections collections = constructor.newInstance(null);
        //warning:Replace "collections" by "Collections"
        collections.sort(list);

        list.forEach(System.out::println);

listIt can be sorted correctly, but it doesn't make any sense.

Guess you like

Origin blog.csdn.net/baidu_40120883/article/details/131882398