使 class 成为 util 的最佳方法?

Best way to make class as util?

我有 class 必须作为 util 使用。我不需要它的实例,它包含的所有内容都是 static 成员和 static 函数。那么最好的方法是什么?在 java 中使用 private 构造函数将其设为 final 作为 Math class 还是仅将其构造函数设为 private 而不将其设为 final

对于util class,你不需要提供constructor.because这个函数是静态的,你可以这样使用:Util.a()

private 构造函数就够了,不需要标记 class final,有了私有构造函数我们就不能 subclass it

如果您创建构造函数 private,您仍然可以使用 reflection 访问它。

更好的方法是抛出 AssertionError

public class Util {    
    private Util() {
        throw new AssertionError("Can't instantiate");
    }
    // static methods
}

下面的代码是实例化私有构造函数

public class Test {
    public static void main(String[] args) {
        try {
            Constructor<Util> utilC = Util.class.getDeclaredConstructor();
            utilC.setAccessible(true);
            Util u = utilC.newInstance(); // instance           
        } catch (Exception e) {
            // exception handling
        }
    }
}