Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindBugs raises a bug called EI_EXPOSE_REP caused by Array

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:

  1. getHobbies(){return hobbies.clone();}
  2. use List instead of Array;

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?

like image 279
Richard H. Avatar asked Nov 15 '17 03:11

Richard H.


Video Answer


2 Answers

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:

  • Return a copy of your array with Arrays.copyOf(..)
  • Convert it to an "Immutable" List with 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.

like image 62
Guillaume F. Avatar answered Nov 02 '22 09:11

Guillaume F.


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"})

like image 26
Vijay Upadhyay Avatar answered Nov 02 '22 11:11

Vijay Upadhyay