I have a problem which I can not understand for the life of me. Why do I get a null pointer here?
In principle I have three class. A singleton class, a factory class and a main. In the Main I call the Singleton class once and let me output something.
Then I call a static method on the factory. Within this factory class there is a static block, which in turn accesses the singleton class. At this moment, however, the instance of the singleton class is null.
I don't really understand this, because with the debugger I also see that the variable is null, but the flow of the calls is actually as expected.
Main.java
package testing;
public class Main {
public static void main(String[] args) {
Singleton.getInstance().getValue();
Factory.build();
}
}
Singleton.java
package testing;
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private String value;
public static Singleton getInstance() {
return INSTANCE;
}
private Singleton() {
configureSingleton();
Factory.build();
}
private void configureSingleton() {
value = "TEST";
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Factory.java
package testing;
public class Factory {
static {
Singleton instance = Singleton.getInstance();
System.out.println(instance.getValue());
}
private Factory() {
}
public static void build() {
System.out.println("Building now");
}
}