问题
I have a method which takes an Array of object as input and stores it in an instance variable. Here is the code that does it but, FindBugs reports it an error saying "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;
}
}
I tried using Arrays.copyOf but, still i am getting this error.
this.objs = Arrays.copyOf(inputs,inputs.length);
How can i fix this FindBugs issue ?
回答1:
You should change your member to private :
private final Hello objs[];
While declaring the member as final prevents it from being assigned after first being initialized, it doesn't prevent its individual entries from being assigned by simply writing :
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
来源:https://stackoverflow.com/questions/33740360/how-to-fix-findbug-error-may-expose-internal-representation-by-incorporating-re