1

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");
    }

}
Community
  • 1
  • 1
  • Couldn't you use a `try{ ... } finally { ... }` to ensure `path` is always set, satisfying the `final` modifier? It would be trivial in your example, but perhaps not in the real world - in any case, it's not clear what value `path` should take in an exception situation. – Anders R. Bystrup Dec 09 '13 at 11:16

1 Answers1

0

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*/     
}
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • `public Configuration() throws IOException, URISyntaxException {` changes to `static throws IOException, URISyntaxException {`? –  Dec 09 '13 at 10:49
  • How would you set `path = propertiesUtility.readProperty("path");` if it's already been declared as `final` without any definition? –  Dec 09 '13 at 10:52
  • 1
    The 'final'ity of the variable only kicks in once it has been defined. So it's ok to declare it without the definition, then set it (eg set from properties) later on, as long as you only do it once – Matt Dec 09 '13 at 10:58
  • @ThreaT: that's odd as I don't. Which IDE / Java compiler are you using? – Bathsheba Dec 09 '13 at 11:51
  • @Bathsheba Sorry, I forgot to put in `path = local_path;` –  Dec 09 '13 at 11:53