java - 从静态外部 util 函数访问内部类

标签 java static

我的类结构大致如下:

final public class Util {
    private Util() {
        throw new AssertionError(); // there is not supposed to exist an instance
    }

    public static DataElem getData() {
        return new Util().new DataElem();
    }

    public class DataElem {
        // class definition
    }
}

正确生成内部类实例的代码取自this线。但我不喜欢每次创建内部类实例时,首先创建外部实例的实例。由于我将 AssertionError 放入其构造函数中,因此它不起作用。

我是否必须携带一个虚拟实例来从内部类创建实例?我不能让像 Util.DataElem 这样的东西工作吗?

最佳答案

你可以让你的内部类静态化

final public class Util {
    private Util() {
        throw new AssertionError(); // there is not supposed to exist an instance
    }

    public static DataElem getData() {
        return  new Util.DataElem();
    }

    private static class DataElem {
        private DataElem(){} // keep private if you just want elements to be created via Factory method
        // class definition
    }
}

然后像这样初始化它

new Util.DataElem();

关于java - 从静态外部 util 函数访问内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24661278/

相关文章:

c++ - "undefined reference"到从静态方法访问的模板类的静态成员

php - php 中的静态变量是否在请求中持续存在?

c# - C# 中静态类初始化的顺序是确定性的吗?

java - "Software caused connection abort: socket write error"的官方原因

java - 当 JSON 对象作为字符串文字插入时,MySQL JSON 列丢失小数精度

javascript - 从静态方法中创建实例

C# 从注册表中获取不带参数的值

java - Spring中基于自定义注解的方法调用?

java - 使用 Jackson 解析器时 Android verifyError 崩溃

java - 是否可以计算 HTML 格式文件中可见文本的行数?