如何防止修改類中的私有字段? - 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章