Item 4 (Item 5 in the 1st ed.) is about Protecting utility class with private constructor. When you have some class with only static methods (e.g. Math), it is useful to protect instantiation of this class. Standard way, how to implement it, is by private default constructor.
public class MuUtilClass {
private MyUtilClass(){}
// other methods omitted
}
Joshua find out, that you can change the accesibility of the constructor by reflection (AccessibleObject.setAccesible). Hence it is better to throw exception inside the constructor.
public class MuUtilClass {
private MyUtilsClass() {
throw new AssertionError();
}
// other methods omitted
}
3 komentáře:
Maybe I ask silly. But why is there the AssertionError? Why an error instead of an exception? I would naturally use the UnsupportedOperationException.
The idea behind is, that you can change accesibility of the constructor by reflection and create instance of the class, that was not designed for instantiation.
You can change accesibility of the method, but you can't change its implementation.
It is not really important if you use Error or Exception. The result is the same. BTW: AssertionError was proposed directly by Joshua.
Well. The idea/reason is pretty clear. My question was focused on "why is suggested AssertionError". I would expect that there was some assert if this error has been throwen. But it wasn't. It could be misleading.
Okomentovat