我如何prevent私人领域中的一类修改? [英] How do I prevent the modification of a private field in a class?

查看:236
本文介绍了我如何prevent私人领域中的一类修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有这个类:

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!"; //!!!

所以这就是问题所在:我访问的类的私人领域从外面!
我怎样才能prevent呢?我的意思是我怎样才能使这个数组不变?这是否意味着每getter方法​​你可以以你的方式以访问私有字段? (我不希望任何库,如番石榴,我只需要知道做这种正确的方式)。

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).

推荐答案

您必须将数组返回一个复制

You must return a copy of your array.

public String[] getArr() {
  return arr == null ? null : Arrays.copyOf(arr, arr.length);
}

这篇关于我如何prevent私人领域中的一类修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆