문제 설명
개체 배열을 설정하는 동안 FindBug 오류 '변경 가능한 개체에 대한 참조를 통합하여 내부 표현을 노출할 수 있음'을 수정하는 방법은 무엇입니까? (How to Fix FindBug error 'May expose internal representation by incorporating reference to mutable object' while setting Array of Objects?)
객체의 배열을 입력으로 받아 인스턴스 변수에 저장하는 메서드가 있습니다. 다음은 이를 수행하는 코드이지만 FindBugs는 "변경 가능한 개체에 대한 참조를 통합하여 내부 표현을 노출할 수 있습니다"라는 오류를 보고합니다.
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 문제를 어떻게 해결할 수 있습니까?
참조 솔루션
방법 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
(by yathirigan、Eran)