系列文章目录
通过反射破坏String的不可变性的小例子,挺有意思的
一、直接放码
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
char[] arr = new char[]{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
// String s = new String(arr, true); // 这个构造是default外部调用不到,我们用反射来
Constructor<String> declaredConstructor = String.class.getDeclaredConstructor(char[].class, boolean.class);
declaredConstructor.setAccessible(true);
String s = declaredConstructor.newInstance(arr, true);
arr[0] = 'a'; // 替换掉数组中的第一个字符 'a'
System.out.println(s); // aello world
}
可以看到String实例构造的时候没有copy出新的字符数组,仍然引用的我们外部数组,外面变字符串跟着变。
不过写完回头一看这么搞也没啥意义…………就酱吧
后记:
笔者抛砖引玉,有指导或意见还望各位大佬不吝赐教