import java.lang.reflect.Field;
public class Main{
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
//反射是和封装背道而驰的1使用反射可能打破封装,代码复杂容易出错
//反射牺牲了编译器自身的检验机制,更需要人工保证代码的正确性
//通过反射方式修改String的内容
//特殊手段不是常规手段
String str="hello";
//(1)获取到String的类对象
//(2)根据value这个字段名字,在类对象中拿到对应字段(仍然是图纸的一部分,相当于局部放大)
Field valueField= String.class.getDeclaredField("value");
valueField.setAccessible(true);
//(3)根据图纸拆开str这个对象,取出里面的零件
//让value这个private的成员也能被访问到
char[] value =(char[])valueField.get(str);
//(4)修改零件内容
value[4]='a';
System.out.println(str);
}
}
这里注意如果使用这个版本的jdk就会有以下报错
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by Main (file:/E:/Mianxiangduixaing/out/production/Mianxiangduixaing/) to field java.lang.String.value
WARNING: Please consider reporting this to the maintainers of Main
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to [C
at Main.main(Main.java:17)
Process finished with exit code 1
使用这个版本的jdk就会编译成功