【问题标题】:Best way to make class as util?将课程设为实用程序的最佳方法?
【发布时间】:2016-07-14 03:09:52
【问题描述】:

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

【问题讨论】:

标签: java oop static static-methods final


【解决方案1】:

private构造函数就够了,不需要标记类final,有了私有构造函数我们不能子类化它

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

更好的方法是 throw 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
        }
    }
}

【讨论】:

    【解决方案2】:

    对于util类,你不需要提供构造函数。因为这个函数是静态的,你可以这样使用:Util.a()

    【讨论】:

    • 我很确定他知道静态方法的好处。他想知道他是否应该使用私有构造函数使类抽象或最终或非最终。他基本上是在问哪一个被认为是最佳实践。
    • 谢谢。在我看来,如果类只提供静态方法,最好使用私有构造函数
    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多