使用 StringBuffer 而不是 String 它将解决您的问题。
public static void main(String[] args) {
StringBuffer s = new StringBuffer("Hello");
changeString(s);
String res = s.toString();
//res = "HelloWorld"
}
private static void changeString(StringBuffer s){
s.append("World");
}
或者,如果您真的只需要使用 String,那么这里是使用反射的解决方案:
public static void main(String[] args) {
String s = "Hello";
changeString(s);
String res = s;
//res = "HelloWorld"
}
private static void changeString(String s){
char[] result = (s+"World").toCharArray();
try {
Field field = s.getClass().getDeclaredField("value");
field.setAccessible(true);
field.set(s, result);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException |
IllegalAccessException e1) {
e1.printStackTrace();
}
}