Issue
Imagine that I have this class:
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!"; //!!!
So this is the problem: I have accessed a private field of a class from outside! How can I prevent this? I mean how can I make this array immutable? Does this mean that with every getter method you can work your way up to access the private field? (I don't want any libraries such as Guava. I just need to know the right way to do this).
Solution
You must return a copy of your array.
public String[] getArr() {
return arr == null ? null : Arrays.copyOf(arr, arr.length);
}
Answered By - OldCurmudgeon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.