首页 > 解决方案 > 在构造函数中调用静态方法有循环依赖问题?

问题描述

我在 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() 有空指针异常。那么这是一个循环依赖吗?如何解决?我尝试使用静态块进行初始化,但仍然失败。

标签: javaconstructorstaticinitializationcircular-dependency

解决方案


根据您的解释的场景示例

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


推荐阅读