I'm trying to make a Version
class for my app that will read version numbers from the manifest at load time and then just reference for example Version.MAJOR
and such wherever I need it elsewhere. However, I'm having issues doing so. Here's my current code:
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);
}
}
}
It won't compile, because the static final
variables might not be initialized (for example if the wrong manifest is loaded or there's an exception loading it) and I can't figure out what the correct procedure to do this is.
Reading this question has given me some insight to not use public static final
. Should I rather be using public static
with getter methods?