Tuesday, 25 November 2014

Preventing the modification of a private field in Java

Let's say you have a class like:

public class Test
{
  private String[] arr = new String[]{"1","2"};    

  public String[] getArr() 
  {
    return arr;
  }
}

Now, I have another class that uses the above class:

Test test = new Test();
test.getArr()[0] ="some value!"; //!!!

Bam! We were able to modify a private field outside of the class. This not what you want! To avoid this situation, you can use of the following solutions:
  1. Either create a defensive copy:
  2. 
    public String[] getArr() {
      return arr == null ? null : Arrays.copyOf(arr, arr.length);
    }
    
    
  3. If you can use a List instead of an array, Collections provides an unmodifiable list:
  4. 
    public List getList() {
        return Collections.unmodifiableList(list);
    }
    
    

No comments:

Post a Comment