我在类B的构造函数中调用类A的静态方法,并得到ExceptionInInitializerError。
A类和B类都是单例类。我尝试在B的构造函数中调用A的getAInstance()方法,但由于调用getAinstance()的空指针异常而导致了初始化程序错误
public class B{
//B's constructor
private B(){
String res = A.getAInstance().getString();//this line cause null pointer exception
// do something
}
//static method to get B's singleton instance
public static B getBInstance(){
}
当我需要在类C中调用B时,我会执行类似B.getBInstance()。someMethodInB()的操作。然后由于A.getAInstance()具有空指针异常而无法初始化B。那是循环依赖吗?如何解决?我尝试使用静态块进行初始化,但仍然失败。
答案 0 :(得分:-1)
根据您的解释的场景示例
class A
{
private static A a = new A();
private A()
{
}
public static A getInstance()
{
return a;
}
public void methodForA()
{
System.out.println("Method for A !!!!");
}
}
class B
{
private static B b = new B();
private B()
{
A.getInstance().methodForA();
}
public static B getInstance()
{
return b;
}
public void methodForB()
{
System.out.println("Method for B !!!!");
}
}
public class C
{
public static void main(String[] args)
{
B.getInstance().methodForB();
}
}
输出: 方法A !!!! B的方法!!!!
具有循环依赖性的方案的示例
class A
{
private static A a = new A();
private A()
{
B.getInstance().methodForB();
}
public static A getInstance()
{
return a;
}
public void methodForA()
{
System.out.println("Method for A !!!!");
}
}
class B
{
private static B b = new B();
private B()
{
A.getInstance().methodForA();
}
public static B getInstance()
{
return b;
}
public void methodForB()
{
System.out.println("Method for B !!!!");
}
}
public class C
{
public static void main(String[] args)
{
B.getInstance().methodForB();
}
}
输出: 线程“主”中的异常java.lang.ExceptionInInitializerError