java.lang.String
如题。我说的不是修改String的引用。
比如:
String a=new String("abcd");
我想在对象本身上把abcd修改成efgh能不能做到?
------解决方案--------------------
String类是final,在java的定义中是不可变对象。
------解决方案--------------------
不能修改是因为String类没有提供修改内部char[] value;的方法,而且你不能通过继承去扩展它的特征。
------解决方案--------------------
不能修改。

------解决方案--------------------
用反射可以
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());
}
------解决方案--------------------
这个你别想了,java里String的设计就是不能修改的,如果你想出修改的办法了,那你就厉害了,可以到oracle公司寻求一个Java大神职位。
而且为了防止修改String类的行为,把String设置成不能被继承的。
------解决方案--------------------
@see java.lang.reflect.AccessibleObject.setAccessible(boolean)
------解决方案--------------------
也行吧,我刚才说的太绝对了,收回。但反射不算是正常方法。楼主主要是不知道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());
}
JDK7 以前不行吧, 测不了了, 好像是有个长度限制什么的
------解决方案--------------------
用反射可以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());
}
JDK7 以前不行吧, 测不了了, 好像是有个长度限制什么的
java 8 测试通过。