利用反射,更改string对象的value数组以达到改变string值。
package test;
import java.lang.reflect.Field;
import lombok.Value;
public class Test1{
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String string = "kkk1";
string.hashCode();
String string2 = string;
String string3 = string;
printhashCode(string2);
System.out.println(string2);
System.out.println(string3);
}
static void printhashCode(String string) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class class1 = string.getClass();
Field declaredField = class1.getDeclaredField("value");
declaredField.setAccessible(true);
char value[] = "kkk".toCharArray() ;
int a = 10;
Object object = declaredField.get(string);
char[] cha = (char[])object;
cha[2] = 'm';
System.out.println(cha);
}
}
代码我cp到这儿了。
其实也就是利用反射,获取string的value属性的field对象,再通过get获取相应string对象的value属性的值。
再强转为char[],然后更改。