我正在尝试为我的应用程序制作一个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方法吗?
这工作,谢谢。 – Logan