在 java 中构造对象时,可以将 this
作为参数传递给方法吗?
想到这样做让我感到不安,但我不确定这是否肯定是错误的。以下面的假设为例:
public final class A {
private final B b;
private final List<String> words;
public A(B b) {
this.b = b;
words = new ArrayList<String>();
for(int i = 0; i < 10; i++) {
words.add(b.getNextStringFromUser(this));
}
}
public List<String> getWords() {
return words;
}
}
public class B {
// returns a String chosen by the user based on the current state of A
public String getNextStringFromUser(A a) {
List<String> wordsSoFar = a.getWords();
// ... omitted
}
}
在我能想到的情况下,这样做可能是正确的做法,即您想要构造一个从其余代码的角度来看不可变的对象,但是构造函数可能会根据到目前为止指定的状态采取不同的过程(如果谈论部分构造对象的状态有意义的话)。在上面的示例中,用户根据目前选择的字符串选择一个字符串,当它们都被选中时,这个对象应该永远不会再改变。
这种事情可以/可取吗?谢谢。
最佳答案
在构造函数中泄露“this”引用是危险的,尤其是在多线程环境中。您最终可能会得到其他线程不可见的未完全构造的对象。如果从单线程使用它可能表现不错,但是这种错误真的很难找到和修复。因此,如果您的 IDE 将其标记为警告,请不要感到惊讶。
关于java - 在 java 构造期间将 `this` 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18793752/