java - 调用另一个构造函数时有什么方法可以访问 this.toString() 的值吗?

标签 java methods constructor instance

大家说对象是“未初始化状态”的,请引用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/

相关文章:

android - 编译器看不到新方法名称 - 构建问题但运行时错误。 "java.lang.IllegalStateException: Could not find a method"

javascript - 当我将一个空字符串传递给 includes (""时)它总是返回 true 吗?

java - 在Java中,如何创建一个在每个实例中方法都不同的类?

C# .Net Core 依赖注入(inject),向构造函数注入(inject)多个参数

java - 从 session 范围检索 @Named 托管 bean

java - RxJava 2 不告诉错误行

c# - 为什么 C# 不接受带有泛型参数的构造函数要求?

exception-handling - Ninject - 如何在构造过程中识别哪个类抛出异常

java - 如何将 JSON 对象映射到 Spring 对象

java - 发布阶段的Maven测试依赖