This article is mainly for some tool classes, such as java.lang.Math
, , java.util.Arrays
, java.util.Collenctions
etc. 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, Collections
the 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 Collections
instance 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);
list
It can be sorted correctly, but it doesn't make any sense.