čtvrtek 15. ledna 2009

Private constructor

I started read the Bloch's Effective Java, 2nd edition. I read the 1st edition couple years ago. I must say, that second edition is not only a facelift - there are much more items explained. E.g. generics, concurrent api, etc.

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:

Vít Kotačka řekl(a)...

Maybe I ask silly. But why is there the AssertionError? Why an error instead of an exception? I would naturally use the UnsupportedOperationException.

Petr Charvát řekl(a)...

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.

Vít Kotačka řekl(a)...

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.