Returning 'data' may exposed internal arra

2019-03-03 14:20发布

问题:

Consider this

public class Data {

    private final SomeField[] fields;
    .....

    public SomeField[] getFields() {
        return map == null ? null : map.clone();
    }

Security - Method returns internal array

Exposing internal arrays directly allows the user to modify some code that could be critical. It is safer to return a copy of the array.

I get that we should not use clone() to copy objects, rather copy the objects using copy constructor.

But that still copies the internal objects which are references. What are recommended ways to avoid clone() above?

Thanks

回答1:

The utility method Arrays.copyOf(T[] original, int newLength) will create a new array with the same objects from the internal array.

The issue with return the internal array is usually about preventing unintended changes to the contents of the array, which would be shared any other clients. Sharing the contained objects is not usually of the same order of concern but if you are implementing some sort of map your requirements may be more stringent.



回答2:

To solve this problem you must avoid to user ternary operator. Instead of this, you must use if operator.

Example:

public CustomMap[] getMap() { CustomMap[] obj = null;

if (map != null){
   obj = map.clone();
}
return obj;

}

OR

public CustomMap[] getMap() {
    CustomMap[] obj = map == null ? null : map.close();
    return obj;
}

I solve my problem using the abouve code. I think that is mandatory to create a new object explicit. I think.

Regards!