gpt4 book ai didi

java - 在构造函数中初始化公共(public)静态最终变量

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:56 25 4
gpt4 key购买 nike

我正在尝试为我的应用创建一个 Version 类,它将在加载时从 list 中读取版本号,然后仅引用 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 变量可能没有被初始化(例如,如果加载了错误的 list 或加载它时出现异常)而且我不知道是什么执行此操作的正确程序是。

阅读 this这个问题让我对不使用 public static final 有了一些了解。我是否应该将 public static 与 getter 方法一起使用?

最佳答案

如果您确保始终只对 final 字段赋值一次,编译器会很高兴:

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 {
int appcode = 0;
int major = 0;
int minor = 0;
char release = 0;
int build = 0;
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);
}
APPCODE = appcode;
MAJOR = major;
MINOR = minor;
RELEASE = release;
BUILD = build;
}
}

关于java - 在构造函数中初始化公共(public)静态最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14424215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com