与 OP 的问题一样,我必须能够找到一种方法来为要从文件系统上的 .properties 文件中读取的最终字段分配值,因此在此之前我的应用程序无法知道这些值发生了。在应用程序启动时将 .properties 文件的内容读入 Properties 对象后,使用通用方法调用来分配值是一个 Hail Mary 通行证,谢天谢地。它也限制了编号。每次应用程序加载到内存中时,文件必须被读取一次,只需通过代码检查来查看 Properties 对象当前是否为空。但是当然,一旦分配,最终字段的值就不能改变,除非通过操纵字段来改变其“最终”状态'https://stackoverflow.com/a/3301720/1216686 - 鬼鬼祟祟,但我喜欢它!)。代码示例,为简洁起见,省略了典型的运行时错误检查,例如 NPE:
import java.util.Properties;
public class MyConstants {
private static Properties props; // declared, not initialized,
// so it can still be set to
// an object reference.
public static String MY_STRING = getProperty("prop1name", "defaultval1");
public static int MY_INT = Integer.parseInt(getProperty("prop2name", "1"));
// more fields...
private static String getProperty(String name, String dflt) {
if ( props == null ) {
readProperties();
}
return props.getProperty(name, dflt);
}
private static void readProperties() {
props = new Properties(); // Use your fave way to read
// props from the file system; a permutation
// of Properties.load(...) worked for me.
}
// Testing...
public static void main(String[] args) {
System.out.println(MY_STRING);
System.out.println(MY_INT);
}
}
这使您可以将要读入应用程序的属性外部化,并且仍然将用于保存其值的字段标记为“最终”。它还允许您保证最终字段值的返回值,因为 Properties 类中的 getProperty() 允许方法的调用代码传入默认值,以防在外部找不到属性的键值对时使用.properties 文件。