简体   繁体   English

将类作为Hashtable密钥-这是一个好主意吗?

[英]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. 经过一番考虑,我基本上在我的应用程序中实现了缓存,使用了一个哈希表,该哈希表包含Class作为键(该哈希表对应于特定的缓存实体,并继承自AbstractCache ),并由那个课,似乎很方便。

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? 但是将Class作为Hashtable键是一个好主意,还是我应该只使用.canonicalName()或类似的东西?

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. 但是,由于要求可能会根据您的代码运行方式(独立Java应用程序或部署在Web容器,企业服务器等中)而有所不同,因此最好不要这样做。 Classloader leaks are very nasty bugs to track down and solve. Classloader泄漏是非常讨厌的错误,需要跟踪和解决。

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. 您将无法通过其规范名称来区分它们,而由不同的类加载器加载的两个相同的类将产生两个不同的Class实例,并可用作同一映射中的键。

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. 如果要以独立Java应用程序以外的任何其他方式进行部署,请谨慎对待其含义。

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. 类实际上是不可变的单例,因此没有机会使用Class的“错误”实例。

The only time there would be an issue is if there were multiple ClassLoaders involved but this is rare in most apps. 唯一会出现问题的是是否涉及多个ClassLoader,但这在大多数应用程序中很少见。

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

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