I am trying to write a method in a class which could be invoked several times, each time modifying one of the class’ fields. However, I need to new the object and set the field’s value to it if I want to modify it, but if do this inside the method, the reference seem to be lost and the field left unchanged after the calling.
Public class A {
private Immutable a; //Immutable class
private Immutable b;
public void modify(Immutable k,int v) {
k=new Immutable(v); //Now I am trying to pass
//a and b as parameters but they remain unchanged
}
}
Is there any way to pass the name of the field into the method (e.g., change the method modify(Immutable k, int v) to modify(String kName, int v), then use the name of the field to access it?
Thanks for any inputs!
Java does not support Call-by-name or call-by-reference, only Call-by-value. Your
kvariable (the method parameter) is completely independent from any variable used outside of the class (if there was one at all).You could use Reflection to support passing “a” or “b” (or a Field object), but you should not.
Better have two methods:
If it is more complicated than a single constructor call, factor the common part out to a common method.