Java通过反射修改String的值
直接上代码package com.sagitario.test;import java.lang.reflect.Field;import java.nio.charset.StandardCharsets;public class StringClassTest {public static void main(String[] args) {String a = "a";String b =
·
直接上代码
package com.sagitario.test;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
public class StringClassTest {
public static void main(String[] args) {
String a = "a";
String b = "b";
System.out.println(a+"的hashcode= "+a.hashCode());
try {
swap(a,b);
System.out.println("swap.a="+a);
System.out.println(a+"的hashcode= "+a.hashCode());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println("a="+a+",b="+b);
}
static void swap(String a,String b) throws NoSuchFieldException, IllegalAccessException {
Class class1 = a.getClass();
//通过clazz获取类中的value属性
Field field = class1.getDeclaredField("value");
//需要设置私有属性可以被操作后才能操作属性值
field.setAccessible(true);
field.set(a,b.getBytes(StandardCharsets.UTF_8));
}
}
打印结果
a的hashcode= 97
swap.a=b
b的hashcode= 97
a=b,b=b
JDK 8中还有一种写法:
import java.lang.reflect.Field;
public class HelloWorld {
public static void main(String []args) {
String a = "a";
String b = "b";
System.out.println(a+"的hashcode= "+a.hashCode());
try {
Class class1 = a.getClass();
Field field = class1.getDeclaredField("value");
field.setAccessible(true);
//获取value属性里面的值(内存地址)
char[] temp = (char[])field.get(a);
//通过temp的地址引用 找到真实String对象中的数组,修改数组内的每一个元素
temp[0] = b.charAt(0);
System.out.println(a+"的hashcode= "+a.hashCode());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("a="+a+",b="+b);
}
}
强调JDK 8是因为从jdk9之后,String中value的类型由char[]数组变成了byte[]数组
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)