How can i pass enum parameter by reference in java? Any solution?
+4
A:
In Java you cannot pass any parameters by reference.
The only workaround I can think of would be to create a wrapper class, and wrap an enum.
public class EnumReference {
public YourEnumType ref;
}
And then you would use it like so:
public void someMethod(EnumReference reference) {
reference.ref = YourEnumType.Something;
}
Now, reference will contain a different value for your enum; essentially mimicking pass-by-reference.
jjnguy
2010-10-22 14:02:58
I actually created a generic `IndirectReference<E>` type specifically for this kind of thing. I got tired of passing arrays around.
Jonathan
2010-10-22 14:12:22
@Jon, good call. I don't usually seem to have a problem with pass-by-value. Never seems to get in my way.
jjnguy
2010-10-22 14:13:12
@Jonathan: You could also use `AtomicReference`.
ColinD
2010-10-22 14:33:19
@ColinD I don't generally need the atomicity. Good idea, though, thanks.
Jonathan
2010-10-22 14:37:22
Or just use a return value?
Nick Holt
2010-10-22 15:14:02
@Nick, well if the effect you want is that a reference is changed, then the return type wouldn't be as helpful as actually changing the reference.
jjnguy
2010-10-22 15:26:42
+5
A:
Java is pass by value - always.
You pass references, not objects. References are passed by value.
You can change the state of a mutable object that the reference points to in a function that it is passed into, but you cannot change the reference itself.
duffymo
2010-10-22 14:05:35