Dima
Dima

Reputation: 1374

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?

Upvotes: 9

Views: 3428

Answers (3)

josefx
josefx

Reputation: 15656

If your enum class is only loaded once it will still work.

  • your enum is only used within the loaded plugin
  • the enum has been loaded by a parent classloader of the individual plugin classloaders

If your enum class is loaded by different classloaders it will not work

  • you pass the enum values between different plugins but the application classloader has not loaded the enum. (it can still work if the enum values never cross between plugins)

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.

Upvotes: 10

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

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;
}

Upvotes: 13

b_erb
b_erb

Reputation: 21241

"==" will not work, but you want to use .equals() anyway.

You might be interested in the apache commons lang class: link text

Upvotes: -5

Related Questions