[hyddd的FindBugs分析记录][M V MS] Public static method may expose internal representation by returning array
2009-02-16 14:08 hyddd 阅读(3361) 评论(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.
一个静态的公共函数,它返回了一个私有的静态数组的引用。任何调用这个静态公共函数的代码,都有可能改变这个私有的静态数组。实例代码如下:
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
防止这种问题的方法是:返回一个数组的拷贝,而不直接返回数组引用。如:
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
作者:hyddd
出处:http://www.cnblogs.com/hyddd/
本文版权归作者所有,欢迎转载,演绎或用于商业目的,但是必须说明本文出处(包含链接)。