How can i pass enum parameter by reference in java? Any solution?
Asked
Active
Viewed 1.1k times
10
-
2The normal reason to "pass an argument by reference" is that you want to modify it. You can do this usually in Java because variables are in fact references - however modifying an enum is generally a very bad idea. – DJClayworth Oct 22 '10 at 15:21
2 Answers
15
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
- 305,152
- 44
- 369
- 561
8
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
- 136,852
- 53
- 295
- 323
-
I actually created a generic `IndirectReference
` type specifically for this kind of thing. I got tired of passing arrays around. – Jonathan Oct 22 '10 at 14:12 -
@Jon, good call. I don't usually seem to have a problem with pass-by-value. Never seems to get in my way. – jjnguy Oct 22 '10 at 14:13
-
4
-
@ColinD I don't generally need the atomicity. Good idea, though, thanks. – Jonathan Oct 22 '10 at 14:37
-
@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 Oct 22 '10 at 15:26