What is the preferred Throwable to use in a private utility class constructor?

前端 未结 8 1293
青春惊慌失措
青春惊慌失措 2020-12-14 01:07

Effective Java (Second Edition), Item 4, discusses using private constructors to enforce noninstantiability. Here\'s the code sample from the book:

public fi         


        
8条回答
  •  没有蜡笔的小新
    2020-12-14 01:13

    When the code requires the inclusion of the JUnit as a dependency such as within the maven test scope test, then go straight to Assertion.fail() method and benefit from significant improvement in clarity.

    public final class UtilityClass {
        private UtilityClass() {
            fail("The UtilityClass methods should be accessed statically");
        }
    }
    

    When outside the test scope, you could use something like the following, which would require a static import to use like above. import static pkg.Error.fail;

    public class Error {
        private static final Logger LOG = LoggerFactory.getLogger(Error.class);
        public static void fail(final String message) {
            LOG.error(message);
            throw new AssertionError(message);
            // or use your preferred exception 
            // e.g InstantiationException
        }
    }
    

    Which the following usage.

    public class UtilityClassTwo {
        private UtilityClassTwo() {
            Error.fail("The UtilityClass methods should be accessed statically");
        }
    }
    

    In its most idiomatic form, they all boil down to this:

    public class UtilityClassThree {
        private UtilityClassThree() {
            assert false : "The UtilityClass methods should be accessed statically";
        }
    }
    

    One of the built in exceptions, UnsupportedOperationException can be thrown to indicate that 'the requested operation is not supported'.

     private Constructor() {
        throw new UnsupportedOperationException(
                "Do not instantiate this class, use statically.");
    }
    

提交回复
热议问题