如何防止修改类中的私有字段? - How do I prevent the modification of a private field in a class?

问题:

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?这是否意味着您可以使用每种 getter 方法来访问私有字段? (I don't want any libraries such as Guava. I just need to know the right way to do this). (我不想要任何诸如 Guava 之类的库。我只需要知道正确的方法即可)。


解决方案:

参考一: https://en.stackoom.com/question/108ZZ
参考二: https://stackoom.com/question/108ZZ
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章