Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum vs. class loaders

Tags:

java

enums

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?

like image 905
Dima Avatar asked Nov 26 '10 17:11

Dima


2 Answers

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;
}
like image 66
Sean Patrick Floyd Avatar answered Oct 04 '22 02:10

Sean Patrick Floyd


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.

like image 22
josefx Avatar answered Oct 04 '22 02:10

josefx