问题描述
查看以下代码:
public class ClassA {
private boolean ClassAattr = false;
public ClassA() {
ClassAHandler handler = new ClassAHandler(this);
}
}
public class ClassAHandler extends GeneralHandler {
ClassA ca = null;
public ClassAHandler(ClassA classa) {
this.ca = classa;
}
}
我需要访问 ClassAattr
在某些 ClassAHandler
方法,以及其他属性。有没有办法这样做而不在处理程序构造函数中传递origin类。
I need to access ClassAattr
on some ClassAHandler
methods, among other attributes. Is there a way to do so without passing the origin class in the handler constructor. I don't really like how this solution "looks".
推荐答案
传递 this
到另一个方法/对象从构造函数中可以是相当危险的。
Passing this
to another method/object from inside the constructor can be rather dangerous. Many guarantees that objects usually fulfill are not necessarily true, when they are looked at from inside the constructor.
例如,如果你的类有一个 final
(非 - static
)字段,那么您通常可以将其设置为某个值,而不会更改。
For example if your class has a final
(non-static
) field, then you can usually depend on it being set to a value and never changing.
当你查看的对象当前正在执行它的构造函数时,那个保证不再成立。
When the object you look at is currently executing its constructor, then that guarantee no longer holds true.
构造 ClassAHandler
对象,直到它首先被需要(例如通过在属性的getter中进行延迟初始化)。
As an alternative you could delay the construction of the ClassAHandler
object until it is first needed (for example by doing lazy initialization in the getter of that property).
这篇关于传递“这个”在java构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!