简体   繁体   中英

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.

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. 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...

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:

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*/     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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