0

我创建了一个包含一堆属性值的类。为了初始化该类,我必须调用一些静态方法“configure()”,该方法从 XML 文件对其进行配置。

那个类应该用来存储一些数据,这样我就可以写了

PropClass.GetMyProperty();

configure()从 main 中的一个静态块调用它,所以我可以在任何地方使用它

如果我将某个其他类的静态常量成员设置为我的“PropClass”中的一个值,我会得到 null,

class SomeClass {

   static int myProp = PropClass.GetMyProperty();

}

这可能是因为该表达式是在调用配置之前评估的。我该如何解决这个问题?

我怎样才能强制调用configure()将首先执行?谢谢

4

4 回答 4

5

你可以使用静态代码块来做到这一点

static {
   configure();
}

静态初始化块的语法?剩下的就是关键字 static 和一对匹配的大括号,其中包含在加载类时要执行的代码。取自这里

于 2009-04-12T09:33:24.323 回答
2

我会做以下事情:

class SomeClass 
{
   // assumes myProp is assigned once, otherwise don't make it final
   private final static int myProp;

   static
   { 
       // this is better if you ever need to deal with exceeption handling, 
       // you cannot put try/catch around a field declaration
       myProp = PropClass.GetMyProperty();
   }
}

然后在 PropClass 中做同样的事情:

class PropClass
{ 
    // again final if the field is assigned only once.
    private static final int prop;

    // this is the code that was inside configure.
    static
    {
        myProp = 42;
    }

    public static int getMyProperty();
}

还。如果可能的话,不要让一切都是静态的——至少使用一个单例

于 2009-04-12T15:24:24.667 回答
0

你能不让GetMyProperty()方法检查是否configure()已经被调用吗?这样您就可以调用GetMyProperty()而不必担心我们的对象是否已配置。您的对象将为您处理此问题。

例如

public String getMyProperty() {
   if (!configured) {
      configure();
   }
   // normal GetMyProperty() behaviour follows
}

(如果你想要线程安全,你应该同步上面的内容)

于 2009-04-12T09:32:19.193 回答
-1

伙计,听起来你应该使用Spring Framework(或其他一些依赖注入框架)。在 Spring 中,您已经获得了所需的一切:

  • 用于定义具有可配置属性的 bean 的 XML 格式,无需编写用于读取 XML 和自己初始化 bean 的逻辑。
  • Bean 在您需要它们时被初始化(前提是您以正确的方式访问它们)。最好的方法是将 bean 注入调用者。

不要发明轮子... Spring 是 Java 中最常用的框架之一。恕我直言,没有它就不应该编写大型 Java 应用程序。

于 2009-04-12T14:59:32.900 回答