[英]Initialize a final variable before constructor in Java
这个问题在Java中的构造函数之前扩展了Initialize final变量,因为我对那里提供的答案不满意。
我也有同样的问题。 我有一些需要设置为final
变量,但是我不能这样做,因为我需要将它们设置为需要捕获异常的值,因此除非我将其放入构造函数中,否则就不可能实现。 这样做的问题是,我每次想引用final
static
变量时都必须创建该对象的新实例,而这实际上没有任何意义。
一个示例,其中每次在不同类中引用该对象时,除非创建new
实例,否则无法在构造函数内部或构造函数内部定义path
:
public class Configuration {
private static final String path;
public Configuration() throws IOException, URISyntaxException {
propertiesUtility = new PropertiesUtility();
path = propertiesUtility.readProperty("path");
}
}
您仍然可以使用静态初始化程序,但是需要一些修饰来存储异常,您应在以后的阶段(例如在构造函数中)使用该异常。
private static final String path;
private static final java.lang.Exception e_on_startup;
static {
java.lang.Exception local_e = null;
String local_path = null;
try {
// This is your old Configuration() method
propertiesUtility = new PropertiesUtility();
local_path = propertiesUtility.readProperty("path");
} catch (IOException | URISyntaxException e){
local_e = e;
}
path = local_path; /*You can only set this once as it's final*/
e_on_startup = local_e; /*you can only set this once as it's final*/
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.