コードが Maven テスト スコープ内などの依存関係として JUnit を含める必要がある場合は、メソッド<scope>test</scope>
に直接進みAssertion.fail()
、明快さの大幅な改善の恩恵を受けます。
public final class UtilityClass {
private UtilityClass() {
fail("The UtilityClass methods should be accessed statically");
}
}
テスト範囲外の場合、次のようなものを使用できます。これには、上記のように静的インポートを使用する必要があります。 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
}
}
次の使用法。
public class UtilityClassTwo {
private UtilityClassTwo() {
Error.fail("The UtilityClass methods should be accessed statically");
}
}
最も慣用的な形式では、それらはすべて次のようになります。
public class UtilityClassThree {
private UtilityClassThree() {
assert false : "The UtilityClass methods should be accessed statically";
}
}
組み込み例外の 1 つである UnsupportedOperationException をスローして、「要求された操作がサポートされていない」ことを示すことができます。
private Constructor() {
throw new UnsupportedOperationException(
"Do not instantiate this class, use statically.");
}