【发布时间】:2013-01-03 15:45:04
【问题描述】:
我正在尝试为我的应用程序创建一个 Version 类,该类将在加载时从清单中读取版本号,然后只需在其他地方需要它时引用例如 Version.MAJOR 等。但是,我在这样做时遇到了问题。这是我当前的代码:
public class Version {
public static final int APPCODE;
public static final int MAJOR;
public static final int MINOR;
public static final char RELEASE;
public static final int BUILD;
static {
try {
Class clazz = Version.class;
String className = clazz.getSimpleName() + ".class";
String classPath = clazz.getResource(className).toString();
if (classPath.startsWith("jar")) {
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attr = manifest.getMainAttributes();
APPCODE = Integer.parseInt(attr.getValue("APPCODE"));
MAJOR = Integer.parseInt(attr.getValue("MAJOR"));
MINOR = Integer.parseInt(attr.getValue("MINOR"));
RELEASE = attr.getValue("RELEASE").charAt(0);
BUILD = Integer.parseInt(attr.getValue("BUILD"));
}
} catch (IOException e) {
System.exit(9001);
}
}
}
它不会编译,因为 static final 变量可能没有被初始化(例如,如果加载了错误的清单或加载它时出现异常),我无法弄清楚执行此操作的正确程序是什么.
阅读this 的问题让我对不使用public static final 有了一些了解。我是否应该将 public static 与 getter 方法一起使用?
【问题讨论】:
标签: java initialization constants manifest static-classes