Make a variable final in any given moment (after initialization and eventual code)

Viewed 8947

Is it possible to make a variable final in any given moment? I would like to decide when its immutable, not just with the first assignment.

It would be perfect, if null would not count as an assignment. So if you would initialize it with null, you would still have a wildcard for the first assignment after some code, not necessarily in the constructor.

4 Answers

Just for you to know, the feature is now proposed in a draft: http://openjdk.java.net/jeps/309. It's called dyanmic constant. Check future work section:

  • Surfacing the lazy initialization of constants in the Java language

The value is, therefore, dynamic but, since its value is only set once, it is also constant.

Related