我有一个类的复制构造函数,但Android Studio代码检查抛出了一个我不理解的警告:
的复制构造函数中的可疑赋值"java.util.Arrays.copyOf(other.value,other.value.length("到字段值public class CpuVariable extends BaseIdentifier {
private int memoryType;
private byte[] value;
public CpuVariable(@NonNull CpuVariable other) {
super(other);
this.memoryType = other.memoryType;
if (other.value != null) {
this.value = java.util.Arrays.copyOf(other.value, other.value.length);
}
}
}
将代码更改为
this.value = other.value
将删除警告,但这不是一个选项,因为我需要为字段创建深度副本或克隆。
我是否编码错误,或者忽略或抑制警告是否安全?
这显然是一个假阳性。您的构造函数实际上没有什么问题。
我认为产生此警告的代码是基于此代码的。注意,这不是真正的安卓工作室代码,但有线索表明安卓工作室可能有"借用的";通过某种途径。
如果您查看constructorAssignsAllFields
方法(第63行(,代码的目的似乎是查找复制构造函数复制错误字段的代码错误;例如:
MyClass(MyClass other) {
this.x = other.x;
this.y = other.x; // Ooops
}
但是该方法没有正确处理复制构造函数正在转换其中一个字段的情况。
查看代码,您需要以一种使检查器没有意识到它正在分配给字段的方式编写this.value =
。例如,如果您使用setter方法,类似于以下方法:
public CpuVariable(@NonNull CpuVariable other) {
super(other);
this.memoryType = other.memoryType;
this.value = other.value; // Dummy
if (other.value != null) {
this.setValue(java.util.Arrays.copyOf(other.value, other.value.length));
}
}
如果复制构造函数存在任何其他问题,例如复制构造函数没有复制所有字段,则也可能发生这种情况。在这种情况下,我在IntelliJ中也看到了同样的错误。