构造函数中的 Java 条件以调用父构造函数

标签 java

我有一个以下 Java 类:

public class CharacteristicResponse extends VotableResponse {

    public CharacteristicResponse() {
    }

    public CharacteristicResponse(Characteristic characteristic) {
        super(characteristic);

        this.characteristicId = characteristic.getId();
        this.name = characteristic.getName();
        this.nameSlug = characteristic.getNameSlug();
        this.description = characteristic.getDescription();
        this.valueType = characteristic.getValueType();
        this.visualMode = characteristic.getVisualMode();

        ...

    }

}

我想向构造函数添加额外的参数,以便能够控制 super 构造函数调用..例如如下所示:

public CharacteristicResponse(Characteristic characteristic, Boolean detailed) {
    if(detailed) {
        super(characteristic);
    }
...

}

从 Java 的角度来看,上面的示例是不可能的,因此我正在寻找一种解决方案,如何以其他方式完成它。

最佳答案

您在评论中说过:

Currently I have a pretty deep chain of a nested super calls.. so I was wondering there is an elegant way how it can be done with no needs to rewrite a lot of code..

为了不让情况发生太大变化,我基本上看到了三个选择:

  1. detailedfalse 且具有 VotableResponse(Characteristic) 的情况下,您可以传递 null处理获取null:

    super(detailed ? characteristic : null);
    
  2. 如果 detailed 为 true,您始终可以调用 super(),然后立即通过 setter 设置characteristic

    super();
    if (detailed) {
        super.setCharacteristic(characteristic);
    }
    
  3. 您可以将标志传递到链上,并让沿途的每个类适本地处理它。

关于构造函数中的 Java 条件以调用父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456384/

相关文章:

java - 如何创建我的抽象类的无名派生类的对象?

java - StringBuilder 类似PreparedStatement

java - 初始化复数JAVA

java - Spring Boot Thymeleaf 显示不工作

java - 内容提供商

java - 如何重写compareTo方法?

java - 在Java中使用反射来设置方法的参数

java - 我们可以对 jaxb 全局绑定(bind)强制限制以映射 xs :dateTime to java. util.Date

java - 如何将 BigDecimal (Java) 值存储在 Real (SQlite) 列中?

java - 运行配置以在 IntelliJ IDEA 中调试 Bukkit/Minecraft 插件?