代码改变世界

[hyddd的FindBugs分析记录][M V MS] Public static method may expose internal representation by returning array

2009-02-16 14:08  hyddd  阅读(3318)  评论(0编辑  收藏  举报

[M V MS] Public static method may expose internal representation by returning array [MS_EXPOSE_REP]

A public static method returns a reference to an array that is part of the static state of the class. Any code that calls this method can freely modify the underlying array. One fix is to return a copy of the array.

 

一个静态的公共函数,它返回了一个私有的静态数组的引用。任何调用这个静态公共函数的代码,都有可能改变这个私有的静态数组。实例代码如下:

public static void main(String args[]) throws Exception{
        String[] strs 
= Test.getStrs();
        strs[
0= "123";
        Test.myTest();
}
    
public class Test {
    
private static String[] strs = new String[10];
    
    
public static String[] getStr(){
        
return strs;
    }
    
public static void myTest(){
        System.out.println(strs[
0]);
    }
}

运行结果是:123

 

防止这种问题的方法是:返回一个数组的拷贝,而不直接返回数组引用。如:

public static String[] getStr(){
        
return strs.clone();
}

 

 

注意:这个BUG和下面这两个BUG比较类似,可以比较一下:>

[M V EI2] May expose internal representation by incorporating reference to mutable object

[M V EI] May expose internal representation by returning reference to mutable object