如何修改传入Java方法的枚举
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();
在上面的示例中,如何修改 alter
方法内的变量 myResult
?由于 Java 是按值传递的,因此该示例只是将其值分配给 this.result
。
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 this.result
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
基本上,你不能,因为 Java 是按值传递的。
在 Java 中,最接近引用传递行为的是创建一个带有 getter 和 setter 的“holder”类;例如
,您可以将
alter()
编写为:请注意,这不是真正的按引用传递。
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.
Then, you could write
alter()
as: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).
简单地说,用 Java 是做不到的。
Simply put, you can't do it in Java.
由于 myResult 是类字段,因此您可以在需要时通过分配其他值来更改它:
myResult = Result.MORE;
。您在哪里编写此代码并不重要。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.