gpt4 book ai didi

java - 如何在Java中实现构造函数包装?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:12 24 4
gpt4 key购买 nike

这就是我想要做的(在 Java 1.6 中):

public class Foo {
public Foo() {
Bar b = new Bar();
b.setSomeData();
b.doSomethingElse();
this(b);
}
public Foo(Bar b) {
// ...
}
}

编译器说:

call to this must be first statement in constructor

有什么解决方法吗?

最佳答案

你可以这样实现它:

public class Foo {
public Foo() {
this(makeBar());
}
public Foo(Bar b) {
// ...
}
private static Bar makeBar() {
Bar b = new Bar();
b.setSomeData();
b.doSomethingElse();
return b;
}
}

makeBar 方法应该是静态的,因为对应于 this 的对象在您调用该方法时不可用。

顺便说一下,这种方法的优点是它确实将一个完全初始化的 Bar 对象传递给 Foo(Bar)。 (@RonU 指出他的方法没有。这当然意味着他的 Foo(Bar) 构造函数不能假定其 Foo 参数处于最终状态。这可以是有问题。)

最后,我同意静态工厂方法是这种方法的一个很好的替代方法。

关于java - 如何在Java中实现构造函数包装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3881614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com