如何在设置对象数组时修复 FindBug 错误 'May expose internal representation by incorporating reference to mutable object'?
How to Fix FindBug error 'May expose internal representation by incorporating reference to mutable object' while setting Array of Objects?
我有一个方法将对象数组作为输入并将其存储在实例变量中。这是执行此操作的代码,但是 FindBugs 报告了一个错误 "May expose internal representation by incorporating reference to mutable object".
public final class HelloWorld
{
public final Hello objs[];
public HelloWorld(Hello[] inputs)
{
this.objs = inputs;
}
}
我尝试使用 Arrays.copyOf 但是,我仍然收到此错误。
this.objs = Arrays.copyOf(inputs,inputs.length);
我该如何解决这个 FindBugs 问题?
您应该将您的会员更改为私人会员:
private final Hello objs[];
虽然将成员声明为 final 会阻止它在首次初始化后被分配,但它不会阻止通过简单地编写来分配其各个条目:
Hello[] harr = {new Hello(), new Hello()};
HelloWorld hw = new HelloWorld(harr);
hw.objs[1] = new Hello(); // this would mutate the contents of your array member
我有一个方法将对象数组作为输入并将其存储在实例变量中。这是执行此操作的代码,但是 FindBugs 报告了一个错误 "May expose internal representation by incorporating reference to mutable object".
public final class HelloWorld
{
public final Hello objs[];
public HelloWorld(Hello[] inputs)
{
this.objs = inputs;
}
}
我尝试使用 Arrays.copyOf 但是,我仍然收到此错误。
this.objs = Arrays.copyOf(inputs,inputs.length);
我该如何解决这个 FindBugs 问题?
您应该将您的会员更改为私人会员:
private final Hello objs[];
虽然将成员声明为 final 会阻止它在首次初始化后被分配,但它不会阻止通过简单地编写来分配其各个条目:
Hello[] harr = {new Hello(), new Hello()};
HelloWorld hw = new HelloWorld(harr);
hw.objs[1] = new Hello(); // this would mutate the contents of your array member