简体   繁体   English

枚举与类加载器

[英]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? 在这种情况下,我仍可以期望操作“ ==”将对枚举值起作用吗?

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. 顺便说一句,使用equals()也无济于事。 Here's the implementation of Enum.equals(Object) in Java 1.6: 这是Java 1.6中Enum.equals(Object)的实现:

public final boolean equals(Object other) { 
    return this==other;
}

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. Java使用对象实例来表示不同的枚举值,这些实例中的每个实例都作为静态字段存储在枚举类中。 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. == operator仅比较引用,并且不知道表示枚举值的多个实例,因此它将无法匹配由不同类加载器加载的值。

"==" will not work, but you want to use .equals() anyway. "=="将不起作用,但是无论如何您都想使用.equals()

You might be interested in the apache commons lang class: link text 您可能对apache commons lang类感兴趣: 链接文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM