Is there a solution to use a final variable in a Java constructor? The problem is that if I initialize a final field like:
private final String name = \"a na
Another possiblity is to initialize the field in an instance initializer blocK:
public class Foo {
final String bar;
{
System.out.println("initializing bar");
bar = "created at " + System.currentTimeMillis();
}
public Foo() {
System.out.println("in constructor. bar=" + bar);
}
public static void main(String[] args) {
new Foo();
}
}
private static final String name = getName();
where getName() is a static function that gets you the name.
In that case, you might as well make it static, too. And Java convention is to name such constants in ALL_CAPS.