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. Here's the implementation of Enum.equals(Object)
in Java 1.6:
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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With