传递“这个"在java构造函数中 [英] Passing "this" in java constructor

查看:18
本文介绍了传递“这个"在java构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看以下代码:

公共类 ClassA {私有布尔 ClassAattr = false;公共类A(){ClassAHandler handler = new ClassAHandler(this);}}公共类 ClassAHandler 扩展了 GeneralHandler {ClassA ca = null;公共 ClassAHandler(ClassA classa) {this.ca = classa;}}

我需要在某些 ClassAHandler 方法以及其他属性上访问 ClassAattr.有没有办法在不传递处理程序构造函数中的原始类的情况下这样做.我真的不喜欢这个解决方案的外观".

解决方案

从构造函数内部将 this 传递给另一个方法/对象可能相当危险.当从构造函数内部查看时,对象通常实现的许多保证不一定是正确的.

例如,如果你的类有一个 final(非static)字段,那么你通常可以依赖它被设置为一个值并且永远不会改变.>

当您查看的对象当前正在执行其构造函数时,该保证不再成立.

作为替代方案,您可以延迟 ClassAHandler 对象的构建,直到第一次需要它(例如通过在该属性的 getter 中进行延迟初始化).

Look into the following code:

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;
    }
}

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".

解决方案

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.

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.

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构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆