I just stumbled over this question about comparing enum values using ==
vs. .equals()
. The common consent is, that it's absolutely ok to use ==
as only one enum constant can exist at a time. This was my first thought, too.
But: What about using two (or more) ClassLoaders loading the same class. Not necessarily a enum class. Any class containing static constants.
Imagine the following:
class ContainsConstants {
public static final Object DEMO_CONSTANT = new Object();
}
Lets reference this value from within another class:
class Pojo {
public final Object myField = ContainsConstants.DEMO_CONSTANT;
}
Now create two Pojo instances using clazz.newInstance()
with clazz being loaded by different ClassLoaders and compare myField
to each other and to ContainsConstants.DEMO_CONSTANT
:
Thread.currentThread().setContextClassLoader(classLoader1);
Pojo pojo1 = instantiatePojoReflectivelyFromClassLoadedBy(classLoader2);
Pojo pojo2 = instantiatePojoReflectivelyFromClassLoadedBy(classLoader3);
if (pojo1.myField == pojo2.myField) {
// what happens?
}
if (ContainsConstants.DEMO_CONSTANT == pojo1.myField) {
// what happens?
}
Question: Will both fields be equal? If not, would an equals method even solve this problem, as it might use static stuff internally (like Strings)?