我有一个以下 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..
为了不让情况发生太大变化,我基本上看到了三个选择:
在
detailed
为false
且具有VotableResponse(Characteristic)
的情况下,您可以传递null
处理获取null
:super(detailed ? characteristic : null);
如果
detailed
为 true,您始终可以调用super()
,然后立即通过 setter 设置characteristic
。super(); if (detailed) { super.setCharacteristic(characteristic); }
您可以将标志传递到链上,并让沿途的每个类适本地处理它。
关于构造函数中的 Java 条件以调用父构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456384/