简体   繁体   English

在Java中的构造函数之前初始化最终变量

[英]Initialize a final variable before constructor in Java

This question extends Initialize final variable before constructor in Java as I was not satisfied with the answer provided there. 这个问题在Java中的构造函数之前扩展了Initialize final变量,因为我对那里提供的答案不满意。

I have the same question. 我也有同样的问题。 I have variables that I need to be set as final but I cannot do so because I need to set them to values that require exceptions to be caught thus making it impossible unless I put them in the constructor. 我有一些需要设置为final变量,但是我不能这样做,因为我需要将它们设置为需要捕获异常的值,因此除非我将其放入构造函数中,否则就不可能实现。 The problem with that is that I then have to make a new instance of the object every time I want to reference the final static variables which doesn't really make sense... 这样做的问题是,我每次想引用final static变量时都必须创建该对象的新实例,而这实际上没有任何意义。

An example where path cannot be defined outside of the constructor nor inside the constructor unless a new instance is created each time the object is referenced from a different class: 一个示例,其中每次在不同类中引用该对象时,除非创建new实例,否则无法在构造函数内部或构造函数内部定义path

public class Configuration {

    private static final String path;

    public Configuration() throws IOException, URISyntaxException {
        propertiesUtility = new PropertiesUtility();
        path = propertiesUtility.readProperty("path");
    }

}

You can still use a static initialiser but you need some some embellishments for storing an exception which you ought to pick up at a later stage (such as in a constructor). 您仍然可以使用静态初始化程序,但是需要一些修饰来存储异常,您应在以后的阶段(例如在构造函数中)使用该异常。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM