我在类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()的操作。那么我不能初始化B,因为A.getAInstance()有空指针异常。那么这是循环依赖吗?如何修复它?我尝试使用静态块进行初始化,但仍然失败。
发布于 2019-01-25 03:20:18
根据您的解释场景示例
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();
}
}
输出:线程"main“java.lang.ExceptionInInitializerError中的异常
https://stackoverflow.com/questions/54354391
复制相似问题