How do I prevent the modification of a private field in a class?

前端 未结 10 1772
Happy的楠姐
Happy的楠姐 2020-12-22 16:45

Imagine that I have this class:

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

  public String[] getArr() 
  {
    return arr;
         


        
10条回答
  •  礼貌的吻别
    2020-12-22 17:40

    Returning an unmodifiable list is a good idea. But a list that is made unmodifiable during the call to the getter method can still be changed by the class, or classes that are derived from the class.

    Instead you should make it clear to anybody that extends the class that the list should not be modified.

    So in your example it could lead to the following code:

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class Test {
        public static final List STRINGS =
            Collections.unmodifiableList(
                Arrays.asList("1", "2"));
    
        public final List getStrings() {
            return STRINGS;
        }
    }
    

    In the above example I've made the STRINGS field public, in principle you could do away with the method call, as the values are already known.

    You could also assign the strings to a private final List field made unmodifiable during construction of the class instance. Using a constant or instantiation arguments (of the constructor) depends on the design of the class.

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class Test {
        private final List strings;
    
        public Test(final String ... strings) {
            this.strings = Collections.unmodifiableList(Arrays
                    .asList(strings));
        }
    
        public final List getStrings() {
            return strings;
        }
    }
    

提交回复
热议问题