简体   繁体   中英

Class as Hashtable key — is it a good idea?

After some consideration, i implemented caching in my application, basically, using a hashtable that contains Class as a key (which is the class that corresponds to a particular cached entity and inherits from an abstract AbstractCache ) and the concrete cache object that is made from that class, which seems quite convenient.

But is it a good idea to have Class as a Hashtable key, or should i probably use just the .canonicalName() or something like that instead?

If you never need to unload classes, it's probably not an issue. But since requirements may vary based on how your code is run (stand-alone Java app or deployed in web container, enterprise server etc.) it might be wiser not to do this. Classloader leaks are very nasty bugs to track down and solve.

Using the canonical name would seem to be a much better solution. Do keep in mind the other challenge, though: if you have multiple classloaders that might load the same class, those classes will still be considered incompatible. You wouldn't be able to differentiate them by their canonical name, while two identical classes loaded by different classloaders would yield two distinct Class instances and could be used as keys in the same map.

If you don't have very specific classloader constraints or requirements, go with the canonical name. If you're deploying as anything else than a stand-alone Java application, be vary wary of the implications.

Sounds fine to me. I have done this in the past. Classes are effectively immutable singletons so there's no chance of using the "wrong" instance of a Class.

The only time there would be an issue is if there were multiple ClassLoaders involved but this is rare in most apps.

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