【发布时间】:2018-06-14 19:02:13
【问题描述】:
假设我有一个包含两个静态最终变量的类,其中一个由另一个类导入。例如,
// File 1
import static com.company.Dependency.y;
class Import {
// Some code...
}
和
// File 2
class Dependency {
public static final Something y = new Something();
private static final Otherthing x = new Otherthing();
// Some code...
}
在两个静态字段中,x 仅与类 Dependency 的实例相关,例如 Dependency 对象的数量,并且初始化成本很高。我不想初始化x,除非至少实例化了一个依赖类的实例。但在这种情况下,import static 语句会意外触发x 的初始化。处理这种情况的最佳做法是什么?
这是我当前的实现。不幸的是,它没有保留 x 的最终属性:
class Dependency {
public static final Something y = new Something();
private static Otherthing x = null;
public Dependency() {
if (Dependency.x == null) {
x = new Otherthing();
}
}
}
【问题讨论】:
-
创建字段
private,忽略它不是final,写一个staticgetter。请记住,您当前的实现不是线程安全的。 -
因为可以从多个线程调用构造函数,您可能还需要考虑同步检查和分配
x的代码。
标签: java import static initialization