java - 一个枚举问题
我在我的应用程序(java)中遇到了一个奇怪的问题。
我有一个枚举。类似的东西
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
,在另一个类中,我
MyEnum.valueA.setObj(new Obj(...))
简要介绍了这一点 - 我有一个带有私有实例成员的枚举,该实例成员有一个集合和一个获取。
到目前为止一切顺利 -
唯一让我惊讶的是,稍后我查看 MyEnum.valueA().obj 的值是 null。
没有任何东西可以将值更新为 null,我什至在构造函数中给了它一个默认值,但稍后我仍然看到它为 null。
有什么建议吗?
I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
枚举应该是不可修改的类,因此您不应该真正这样做。如果您希望修改基于类型的对象(例如枚举)的状态,您应该使用带有嵌入常量的最终类方法。下面是一个基于类的方法的示例,具有可修改的名称和不可修改的名称......
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
枚举的目的是表示常量值。将字段设置为常量值没有任何意义。
您应该将字段声明为
final
,并使用构造函数来初始化所有字段。The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as
final
, and use the constructor to initialize all of them.作为参考,以下代码按预期工作:
For reference, the following code works as expected:
这个问题的原因是db40框架。它使用反射从数据库加载枚举。这是有据可查的。
http://developer.db4o.com/Forums/tabid/98 /aft/5439/Default.aspx
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx