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