Gikkman Gikkman - 2 months ago 9
Java Question

Java - Change a parameter object inside anonymous method

I came across this today and I can't quite get my head around what is happening.

The intention is to create an anonymous method that can change the argument objects. I though I came up with a smart way of passing values and modifying them between different objects without having explicit knowledge of the other object, but something is awry.
The following code below outlines the general problem:

void foo() {
String a = "foo";

MethodMap.addMethod("1", new Method() {
@Override
public void execute(Object ... args) {
args[0] = "bar";
}
} );
MethodMap.invoke("1", a);
System.out.println(a);
}

class MethodMap {
private static Map<String, Invocation> map = new HashMap<>();

public static boolean addMethod(String key, Invocation method) {
map.put(key, method);
}

public static void invoke(String key, Object ... args){
map.get(key).execute(args);
}
}

public interface Invocation {
public void execute(Object ... args);
}


My intention was that this code should output bar, but it outputs foo. I'm not quite sure why though. Isn't Java-objects passed by reference? In that case, shouldn't I be able to modify them?

Could someone please explain what it is I am missing?

My knowledge of terminology in the field might actually be what's limiting my ability to search for this online, cause I have no idea what words to Google.

Thanks // Simon

Answer

Java is always pass-by-value. You simply cannot change what a local variable points to other than reassigning it in the method in which it is declared. Unlike some other languages, you cannot pass a "by reference" and have another method update what it points to.

By specifying arg[0] = "bar", you are successfully assigning the value "bar" to the first element of your parameter array. But this has no effect on a.

See: