62,629
社区成员
发帖
与我相关
我的任务
分享
不过反射这种方法有点“奇技淫巧”之感,彻底破坏代码严谨性。。
实际项目中除非万不得已只此一条路,不然要么被上司骂死,要么被后期维护人员群殴
明白了,感谢大家。
我的类中有一个String,修改的时候,直接就让他=另一个引用了,我就怕如果能修改,在我的程序中把其中一个对象的修改了,到时候另一个对象也发生变化。

public static void main(String[] args) throws Exception {
final String str = "abcd";
System.out.println(str);
edit(str, "efgh");
System.out.println(str);
}
public static void edit(final String str, String newValue) throws Exception {
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
field.set(str, newValue.toCharArray());
}