The following is an example class
public class Utils {
private static Function<String,Type2> typeFunc = null;
public static void setTypeFunction(Function<String,Type2> func) {
Utils.typeFunc = func;
}
public static Type2 getTypeFuncResult(String input) {
return Utils.typeFunc.apply(input);
}
}
And then the calling class
// Other code
String input = dummy;
// Setup func
Function<String,Type2> testFunc = s->new Type2(s);
// Call - it's all good
Utils.setTypeFunction(testFunc);
Utils.getTypeFuncResult(input);
// Nullify the func lambda output
testFunc = s->null;
// Now call again
Utils.getTypeFuncResult(input); // Expected NULL, but still gets a Type2 object
I am trying to understand this in the context of the following:
a) Reference change for testFunc
is not visible to static Utils.typeFunc
- this means memory is probably being wasted without me knowing.
b) Lambda's are evaluated differently with reference to static references.
c) Anything else.
I believe this is more rudimentary Java, but was wondering if I can get any pointers.
UPDATE
I know java to be pass-by-"copy of the value of" reference. But here is the thing for comparisoni:
TypeA class:
public class TypeA {
private int input = 0;
public TypeA() {
}
public TypeA(int input) {
this.input = input;
}
public void displayInput() {
System.out.println(this.input);
}
public void setInput(Integer i) {
this.input = i;
}
public int getInput() {
return this.input;
}
}
TypeB Class:
public class TypeB {
private TypeA typeA;
public TypeB() {
}
public void setTypeA(TypeA typeA) {
this.typeA = typeA;
}
public TypeA getTypeA() {
return this.typeA;
}
}
Now let's run a test
@Test
public void runReferenceTest() {
TypeB typeB = new TypeB();
TypeA typeA = new TypeA();
typeB.setTypeA(typeA);
System.out.println(typeB.getTypeA().getInput()); // should be 0
typeA.setInput(2);
System.out.println(typeB.getTypeA().getInput()); // Should be 2
typeA = null;
System.out.println(typeB.getTypeA().getInput()); // Shows as 2
}
Based on the above, am I right to conclude that:
a) As long as the "copy" of the reference value is alive, the changes will get reflected.
b) If the reference is set to NULL, the copy will not get updated because it's a copy?