java 类 引用,Java类彼此引用

I have two java class files. Each of them has methods the other one uses.

public class class1{

class2 c2 = new class2();

m1(){

c2.ma();

m2();

}

m2(){}

}

public class class2{

class1 c1 = new class1();

ma(){}

mb(){

c1.m2();

}

}

The lines

class1 c1 = new class1();

and

class2 c2 = new class2();

refer to each other causing an infinite loop, resulting in a java.lang.StackOverflowError error.

Is there some way to have the classes refer to each other or do I have no choice but to transfer all of my methods into a single class?

解决方案

As is said above, this is a sign of code smell.

Having a setter to set the method afterwards is not satisfactory, as you have an object in an indeterminate state, until the setters are called.

Although using a dependency framework such as Spring can help solve the above problem, if you use constructor injection, then you cannot have cyclic dependencies either! But at least when a bean is injected, you are sure it is not half constructed.

If you don't want to use a dependency injection framework, consider a factory pattern where both objects are created by a factory method, which returns a tuple (or a container object in the case of Java which has no native support for tuples) containing the fully constructed objects.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值