简体   繁体   中英

Will the use of Class as key for a HashMap cause undesireable effects?

Consider the following:

Map<Class<?>, Object> myMap = new HashMap<Class<?>, Object>();
Foo fooObject = New Foo();
myMap.put(fooObject.getClass(), fooObject)

Notice that java.lang.Class does not implement the hashCode() method itself, but inherits it from java.lang.Object implicitly. I verified this in JDK 1.8.

Is java.lang.Class safe to use as a key for a java.util.HashMap ? Will myMap.get(Foo.class) always return the values which I put like myMap.put(fooObject.getClass(), fooObject) ? Consider the software to have various classloaders and serialization mechanisms. Will it still be the same result? If not... What would be an alternative?

Off the top of my head, would there be any reason to just not use the string class names? Eg instead use:

myMap.put("Foo", fooObject);

If you are paranoid that maybe there could be more than one Foo class in scope, you could use the full canonical name:

myMap.put(Foo.class.getCanonicalName(), fooObject);

Class的实例对于ClassLoader是唯一的,因此不需要覆盖hashCodeequals

Is java.lang.Class safe to use as a key for a java.util.HashMap?

Yes.

Will myMap.get(Foo.class) always return the values which I put like myMap.put(fooObject.getClass(), fooObject)?

Yes.

Using a Class object as a key in a HashMap is safe. The Class class inherits the Object::equals and Object::hashCode methods. Thus equals for Class objects is testing object identity.

This is the correct semantics for type equality in Java. The implementation of the ClassLoader::defineClass method ensures that you can never get two different Class objects representing the same Java type.

However, there is a wrinkle. The Java Language specification ( JLS 4.3.4 ) states this:

At run time, several reference types with the same binary name may be loaded simultaneously by different class loaders. These types may or may not represent the same type declaration. Even if two such types do represent the same type declaration, they are considered distinct.

(The binary name is related to the FQDN of a named type, and takes account of anonymous classes, and array types.)

What this means is that if you (successfully) call ClassLoader::defineClass for classes with the same fully qualified name in two different classloaders, you will get different Java types. Irrespective of the bytecodes you used. Furthermore, if you attempt to cast from one type to the other one, you will get a class cast exception.


Now the question is does this matter in your use-case?

Answer: probably not.

  • Unless you (or your framework) are doing tricky things with classloaders, the situation does not arise.

  • If it does, then you probably need the two types (with the same FQDN and different classloaders) to have the different entries in the HashMap . (Because the types are different!)

  • But if you need the two types to have the same entry, then you can use the FQDN for the class as the key, which you can obtain using Class::getCanonicalName . If you need to cope with array classes, etc, then use Class::getName which returns the binary name for the type.


What about serialization mechanisms?

A Class object cannot be serialized using Object serialization, since Class does not implement Serializable . If you implement / use some other serialization mechanism that does support the serialization of Class objects, then that mechanism needs to be compatible with JLS 4.3.4.

There is a difference between run-time and compile-time type. It is possible to simultaneously load multiple classes of the same fully-qualified class name, if (and only if) they are loaded by different class loaders. Then such classes are distinct run-time types, and cannot be cast to one another , even if they are identical.

Hence the answer to your question depends simply on which effect you consider desirable:

  • If you desire to treat those separately loaded and incompatible classes as distinct in your map, use Class as the key. There will never be more than one live instance of Class with the same name and loader, so the Class class correctly does not override the hashCode and equals methods. So it is fine to use it as a HashMap key, although IdentityHashMap will give the same behavior, probably more efficiently.

  • If you desire to distinguish classes based only on their name, regardless of how (or whether) they were loaded, then use their string name as the map key.

@talex I tested it like below and you seem to be right:

public class ClassUnique {

    public static void main(String [] args) throws ClassNotFoundException {
        Class<?>  c1 = Class.forName("java.util.Date");
        Class<?>  c2 = Class.forName("java.util.Date");

        System.out.println(c1.equals(c2));
    }
}

Output is true

EDIT: @Maarten I think you are right. Especially if you are running within an application container like Websphere or Weblogic there might be multiple class loaders in play which could screw this up. So in the end the simplest correct solution would be to just use the Class instance itself.

I would consider using IdentityHashMap . It does not rely on equals .

This class is designed for use only in the rare cases wherein reference-equality semantics are required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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