java - 在构造函数中调用静态方法有循环依赖问题?
问题描述
我在 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() 有空指针异常。那么这是一个循环依赖吗?如何解决?我尝试使用静态块进行初始化,但仍然失败。
解决方案
根据您的解释的场景示例
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
推荐阅读
- apache - 如何在 SOLR 中搜索包含 [ 和/或 ] 的字段?
- symfony - 如何获取当前登录的角色 symfony?
- r - 如何在一定时间后触发情节悬停?
- python - 无法在 keras 中定义自定义损失函数
- java - 更新后检索数据库列的值
- asp.net - 如何使用敲除和 asp.net 将文件(excel)上传到我的 C 驱动器上的特定位置
- azure - 功能应用程序启动后 TimerTrigger 未触发
- rest - 如何在sails的action2中获取查询参数
- fiware - Orion Admin mashup NGSI 订阅浏览器小部件无法正常工作
- javascript - React 路由器在刷新后渲染组件