Why are public static final array a security hole?

后端 未结 8 1656
盖世英雄少女心
盖世英雄少女心 2020-12-13 13:21

Effective java says:

// Potential security hole!

static public final Thing[] VALUES = { ... };

Can somebody tell me what is t

8条回答
  •  無奈伤痛
    2020-12-13 13:46

    I would also add what Joshua Bloch proposed in Effective Java 3rd edition. Of course we can easily change the value of the array if it is declared as:

    public static final String[] VALUES = { "a", "b" }; 
    
    a.VALUES[0] = "changed value on index 0";
    System.out.println(String.format("Result: %s", a.VALUES[0]));
    

    and we get Result: changed value on index 0

    Joshua Bloch proposed to return copy of array:

    private static final String[] VALUES = { "a", "b" };   
    public static final String[] values()
    {
        return VALUES.clone();
    }
    

    so now when we try:

    a.values()[0] = "changed value on index 0";
    System.out.println(String.format("Result: %s", a.values()[0]));
    

    we get Result: a and that's what we wanted to achieve - the VALUES are immutable.

    There is also nothing bad in declaring public static final a primitives values, Strings or other immutable objects like public static final int ERROR_CODE = 59;

提交回复
热议问题