01 import java.util.*;
02
03 class MySingletonClass {
04 private static final instance = new MySingletonClass();
05 private static final ListMY_STRINGS;
06 static {
07 MY_STRINGS = new ArrayList();
08 }
09 public MySingletonClass() {
10 System.out.println("MY_STRINGS: "+MYSTRINGS);
11 }
12 }
The above will throw a NullPointer Exception on line 10 because the MySingletonClass constructor is called BEFORE the static initialization block is executed. So change it to this:
01 import java.util.*;
02
03 class MySingletonClass {
04 private static final instance;
05 private static final ListMY_STRINGS;
06 static {
07 MY_STRINGS = new ArrayList();
08 instance = new MySingletonClass();
09 }
10 public MySingletonClass() {
11 System.out.println("MY_STRINGS: "+MYSTRINGS);
12 }
13 }
Now the instance static member variable is not created until AFTER the other static member is initialized. So the constructor can correctly execute the print statement.
No comments:
Post a Comment