大家说对象是“未初始化状态”的,请引用the answer to this question这表明对象引用可以传递、取消引用、从中调用方法以及访问字段之前构造函数终止并且所有字段都已分配(包括 final
字段)。
所以这是用例:
public class Entity {
private final String name;
public Entity() {
this(toString()); //Nope, Chuck Testa
}
public Entity(String name) {
this.name = name;
}
}
编译错误是:
Cannot refer to an instance method while explicitly invoking a constructor.
请注意,toString()
尚未被覆盖,并且是来自 Object
的默认调用。
我当然对这背后的哲学/技术原因很感兴趣,所以如果有人能解释一下,那将是一个了不起的奖励。但我正在寻找一种从默认构造函数调用 toString()
的方法,因为它指向具有更多参数的更具体的构造函数。实际用例有点复杂,最终一直引用到具有四个参数的构造函数,但这并不重要。
我知道我可以做这样的事情......
private static final String TO_STRING_CONSTRUCTOR_ARGUMENT = "aflhsdlkfjlkswf";
public Entity() {
this(TO_STRING_CONSTRUCTOR_ARGUMENT);
}
public Entity(String name) {
this.name = name == TO_STRING_CONSTRUCTOR_ARGUMENT ? toString() : name;
}
...但这似乎是一个非常不优雅的解决方案。
那么,有什么办法可以实现吗?或者有什么推荐的最佳做法来处理这种情况?
最佳答案
我宁愿在创建对象之前不传递 this
。相反,我会这样做:
public class Entity {
private final String name;
public Entity() {
this(null); // or whatever
}
public Entity(String name) {
this.name = name;
}
public String getName() {
return name != null ? name : Objects.hashCode(this);
}
}
如果你能忍受没有最终name
,你可以使用一个初始化 block :
public class Entity {
private String name;
{name = this.toString();}
public Entity() {
}
public Entity(String name) {
this.name = name;
}
}
this
仅在对 this()
或 super()
的所有调用完成后可用。初始化程序在构造函数调用 super()
之后首先运行,并允许访问 this
。
关于java - 调用另一个构造函数时有什么方法可以访问 this.toString() 的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21527523/