使用StringBuffer代替弦,它就會解決您的問題。
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");
}
或者,如果你真的需要所以這裏只使用字符串爲解決使用反射:
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();
}
}
見http://stackoverflow.com/questions/11164675/mutable-strings-in-java – fdomig 2012-08-12 18:32:03
如果你確實需要在返回void的方法中做到這一點,那麼就有一個骯髒的破解。 - > http://blogs.atlassian.com/2008/07/magic_trick_in_java但那通常不是要走的路! – zip 2012-08-12 18:40:08
似乎[請在此輸入鏈接的描述] [1] [1]的副本:http://stackoverflow.com/questions/9183703/passing-a-string-to-a-function – Cyber 2012-08-12 18:50:05