Today I came across this and I canโt understand what is happening.
The goal is to create an anonymous method that can modify argument objects. I, although I came up with a smart way to transfer values โโand change them between different objects without explicit knowledge of another object, but something is wrong. The following code describes a common 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 a bar, but it outputs foo. I'm not quite sure why. Are Java objects passed by reference? In that case, can I change them?
Can someone explain what I am missing?
My knowledge of terminology in this area may indeed be what limits my ability to search this online, because I have no idea what words are for Google.
Thanks // Simon
source share