Returning 'data' may exposed internal array?

安稳与你 提交于 2019-12-02 07:52: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!



来源:https://stackoverflow.com/questions/29472191/returning-data-may-exposed-internal-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!