枚举与类加载器
有时您甚至可能不知道您插入代码的环境有多个类加载器。在这种情况下,我仍然可以期望操作“==”适用于枚举值吗?
Sometimes you may even not know that the environment you plug you code in has more than one class loader. May I still expect that operation "==" will work on enum values in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
多个类加载器可能不是问题,只要枚举只能通过其中之一使用。如果不是这种情况,您将失去枚举的所有好处。
顺便说一句,使用 equals() 也没有帮助。以下是 Java 1.6 中
Enum.equals(Object)
的实现:Multiple classloaders may not be the problem, as long as the enum is only available through one of them. If that is not the case, you lose all the benefits of an enum.
And by the way, using
equals()
doesn't help either. Here's the implementation ofEnum.equals(Object)
in Java 1.6:如果您的枚举类仅加载一次,它仍然可以工作。
如果您的枚举类由不同的类加载器加载,它将不起作用
这样做的原因
Java 使用对象实例来表示不同的枚举值,每个实例都存储为静态字段枚举类。如果枚举加载两次,每个枚举值将由两个不同的对象实例表示。
== 运算符
仅比较引用,并不知道代表枚举值的多个实例,因此它无法匹配不同类加载器加载的值。If your enum class is only loaded once it will still work.
If your enum class is loaded by different classloaders it will not work
The reason why it is this way
Java uses object instances to represent the different enum values, each of these instances is stored as a static field within the enum class. If the enum is loaded twice each enum value is represented by two different object instances. The
== operator
only compares the references and is unaware of the multiple instances representing an enum value, so it will fail to match values loaded by different classloaders."=="
不起作用,但无论如何你都想使用.equals()
。您可能对 apache commons lang 类感兴趣: 链接文字
"=="
will not work, but you want to use.equals()
anyway.You might be interested in the apache commons lang class: link text