How to modify enum passed into Java method
public class Test {
private Result result;
public Test(Result res){
this.result = res;
}
public void alter(){
this.result = Result.FAIL;
}
}
public enum Result{ PASS, FAIL, MORE};
public Result myResult = Result.PASS;
Test test = new Test(myResult);
test.alter();
In the above example, how would I modify the variable myResult
inside the alter
method? Since Java is pass by value, the example simply assigns its value to t开发者_运维问答his.result
.
Basically, you can't, because Java is pass-by-value.
The closest you can get to pass-by-reference behavior in Java is to create a "holder" class with a getter and setter; e.g.
public class ResultHolder {
private Result value;
public ResultHolder(Result initial) { value = initial; }
public void setValue(Result newValue) { value = newValue; }
public Result getValue() { return value; }
}
Then, you could write alter()
as:
public void alter(ResultHolder holder, Result newValue) {
holder.setValue(newValue);
}
Note that this is not real pass-by-reference.
You can't modify the actual enum values. They're essentially classes that are named constants. If you want altered behavior inside an enum instance then you don't want an enum ( if you can alter the object then other consumers of the object can't treat it as a constant).
Simply put, you can't do it in Java.
Since myResult is the class field you can change it when you wish by assigning other value:
myResult = Result.MORE;
. it does not matter where do you write this code.
public class Test {
private Result result;
public Test(Result res){
this.result = res;
}
public Result alter(){ // signature changed
this.result = Result.FAIL;
return this.result; // new
}
}
_
public enum Result{ PASS, FAIL, MORE};
public Result myResult = Result.PASS;
Test test = new Test(myResult);
myResult = test.alter(); // change the value
精彩评论