FindBugs raises a bug called EI_EXPOSE_REP with the following description :
EI: May expose internal representation by returning reference to mutable object
Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is a better approach in many situations.
class Person {
private String[] hobbies;
String[] getHobbies(){ return hobbies;}
void setHobbies(String[] hobbies){ this.hobbies = hobbies;}
}
I know some solutions:
What I want to know is why just array raises this bug, a list doesn't have this problem? Why array is so different from other collections?
Findbugs (which is now replaced by Spotbugs) raises a security issue. It is not a bug since it doesn't create an unwanted behavior by itself. But this exposure of the internal data CAN create bugs later in caller methods.
You guessed it, there are two ways to protect your getter against exposure:
Arrays.copyOf(..)
Collections.unmodifiableList(..)
(you can also use List.of(..)
since Java 9)A List
will raise a similar warning unless made unmodifiable.
It's a good practice to use Collections
instead of Arrays
unless you really have a good reason not to.
In some cases, when you have few writes and many reads, the Class CopyOnWriteArrayList
is a great alternative to have a simple immutable list getter.
What I want to know is why just array raises this bug.
It's just a warning. Findbugs displays a severity level next to the report.
Exposure is a medium one for security, but low for bugs.
A list doesn't have this problem?
It does. An ArrayList is just an Array with an additional layer of abstraction.
Why array is so different from other collections?
An Array is a native type, while Collections are not.
The behavior is similar, but you have less control over an Array than you have over a Collection.
I got this issue for byte[] variable in my POJO class. If you want, you can suppress it using an annotation: @SuppressFBWarnings(value = {"EI_EXPOSE_REP", "EI_EXPOSE_REP2"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With