【问题标题】:How should I invoke class static initialization?我应该如何调用类静态初始化?
【发布时间】:2012-08-27 19:37:37
【问题描述】:

我有许多 GUI 元素类型,并在 GUI 加载后直接在代码中使用它们。除非 GUI 加载器需要知道现有元素来创建它们,否则这将是可以的。

public final class VerticalBox extends Element {

    ...

    private static final ElementType type;
    static {
        type = ElementType.register("VerticalBox",
                new ElementType.ICreator() {
                    @Override
                    public Element create(GUI gui) {
                        return new VerticalBox(gui);
                    }
                });
    }

    @Override
    public ElementType getType() {
        return type;
    }
}

最简单的方法是在每个元素类中创建静态init 函数,但我需要为每个元素类调用init

我在 JavaEE 中看到了一些注释,但它们的工作方式似乎相反。我可以从class 获得所有annotations,但不能从annotation 获得classes。我在这个主题上做了很多谷歌搜索。

【问题讨论】:

    标签: java static annotations initialization


    【解决方案1】:

    你想在这里使用某种依赖注入,它将按需初始化。值得关注 Spring Framework、Google Guice 或 Pico Container。

    在大多数情况下,使用静态块是个坏主意,因为您无法完全控制它们,而且它会使单元测试变得非常复杂 - 测试的顺序很重要。

    【讨论】:

      【解决方案2】:

      也许您对 this answer 感兴趣,或者,如果您的课程被拆分为多个您希望保持独立的 jar,那么 ServiceLoader mechanism 可能适合您。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-14
        • 1970-01-01
        • 2014-04-15
        • 2023-03-17
        • 2015-06-19
        • 2018-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多