我创建了一个包含一堆属性值的类。为了初始化这个类,我必须调用一些静态方法"configure()“来从XML文件中配置它。
那个类应该用来存储一些数据,这样我就可以编写
PropClass.GetMyProperty();我从main中的静态块调用configure(),所以我可以在任何地方使用它
但
如果我将其他类静态常量成员设置为"PropClass“中的值,则会得到null,
class SomeClass {
static int myProp = PropClass.GetMyProperty();
}这可能是因为表达式在调用configure之前进行了计算。我该如何解决这个问题?
如何强制首先执行对configure()的调用?谢谢
发布于 2009-04-12 09:33:24
您可以使用静态代码块来做到这一点
static {
configure();
}静态初始值设定器块的语法?剩下的就是关键字static和一对匹配的花括号,其中包含要在装入类时执行的代码。taken from here
发布于 2009-04-12 15:24:25
我会做以下事情:
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();
}还有。如果可能的话,不要让所有东西都是静态的--至少使用singleton。
发布于 2009-04-12 09:32:19
你可以不让GetMyProperty()方法检查configure()是否已经被调用了吗?这样你就可以调用GetMyProperty(),而不必担心我们的对象是否被配置了。您的对象将为您处理此问题。
例如:
public String getMyProperty() {
if (!configured) {
configure();
}
// normal GetMyProperty() behaviour follows
}(如果你想成为线程安全的,你应该同步上面的内容)
https://stackoverflow.com/questions/741512
复制相似问题