[英]enum vs. class loaders
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?
在这种情况下,我仍可以期望操作“ ==”将对枚举值起作用吗?
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. 顺便说一句,使用
equals()
也无济于事。 Here's the implementation of Enum.equals(Object)
in Java 1.6: 这是Java 1.6中
Enum.equals(Object)
的实现:
public final boolean equals(Object other) {
return this==other;
}
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. Java使用对象实例来表示不同的枚举值,这些实例中的每个实例都作为静态字段存储在枚举类中。 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. == operator
仅比较引用,并且不知道表示枚举值的多个实例,因此它将无法匹配由不同类加载器加载的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.