enum vs. class loaders

2020-03-16 07:33发布

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?

标签: java enums
3条回答
Summer. ? 凉城
2楼-- · 2020-03-16 07:43

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-03-16 07:45

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

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

查看更多
家丑人穷心不美
4楼-- · 2020-03-16 07:48

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;
}
查看更多
登录 后发表回答