我有一个应该提供程序路径的类。为此,它确定Windows下的本地和漫游数据路径,并在Linux下获取home的子目录。除此之外,它提供了从其他路径派生的路径。
写
是否安全public class DataDirectory {
public static final File ROAMING;
public static final File LOCAL;
static {
// set ROAMING and LOCAL
}
public static final File PROFILE = doMkdirs(new File(ROAMING, "profiles");
public static final File SETUP = doMkdirs(new File(ROAMING, "setup");
public static final File LOGFILES = doMkdirs(new File(ROAMING, "logfiles");
private static File doMkdirs(File file) {
file.mkdirs();
return file;
}
}
或者我必须这样做
public class DataDirectory {
public static final File ROAMING;
public static final File LOCAL;
public static final File PROFILE;
public static final File SETUP;
public static final File LOGFILES;
static {
// set ROAMING and LOCAL
PROFILE = mkdirsRoaming("profiles");
SETUP = mkdirsRoaming("setup");
LOGFILES = mkdirsRoaming("logfiles");
}
public static final File PROFILE = doMkdirs(new File(ROAMING, "profiles");
public static final File SETUP = doMkdirs(new File(ROAMING, "setup");
public static final File LOGFILES = doMkdirs(new File(ROAMING, "logfiles");
private static File doMkdirs(File file) {
file.mkdirs();
return file;
}
}
为了安全起见?
答案 0 :(得分:0)
我自己以QA风格回答这个问题。
java规范声明the initializers are executed in textual order, as though they were a single block。
这意味着第一个版本是安全的; static { }
块之后的初始值设定项可以使用该块内设置的最终变量。