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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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."=="
will not work, but you want to use.equals()
anyway.You might be interested in the apache commons lang class: link text
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: