How to Fix FindBug error 'May expose internal representation by incorporating reference to mutable object' while setting Array of Objects? [duplicate]

和自甴很熟 提交于 2020-01-15 03:27:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!