在您的示例中有不对的地方。
class Foo { public static void main(String[] args) { String x = "foo"; getString(x); System.out.println(x); } public static void getString(String output){ output = "Hello World" }}在上面的程序中,将输出字符串“ foo”, 而不是 “ Hello World”。
某些类型是可变的,在这种情况下,您可以修改传递给函数的对象。对于不可变的类型(例如
String),您必须构建某种包装类,而可以将其传递给它:
class Holder<T> { public Holder(T value) { this.value = value; } public T value;}然后您可以绕过持有人:
public static void main(String[] args) { String x = "foo"; Holder<String> h = new Holder(x); getString(h); System.out.println(h.value);}public static void getString(Holder<String> output){ output.value = "Hello World"}


