Java map,key = class,value =该类的实例 [英] Java map, key = class, value = instance of that class

查看:312
本文介绍了Java map,key = class,value =该类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我想做什么是可能的,但如果是的话,我想知道如何做。基本上,我想创建一个Map,其中键是一个类( java.lang.Class ),该条目的值是该类的一个实例。目前我已经

I'm not sure what I want to do is possible, but if it is, I want to find out how. Basically, I want to create a Map where the key is a class (java.lang.Class), and value for that entry is an instance of that class. Currently I have

private Map<Class<?>, Object> myMap = new HashMap<Class<?>, Object>();

但是,这意味着任何对象都可以放在地图中。如果有可能,我想制作它,因此只有键中类的实例可以放在地图中。有没有办法使用?对类进行参数化以确保这一点?

However, this means any Object can be placed in the Map. If it is possible, I want to make it, so only an instance of the class in the key can be placed in the map. Is there any way to use the ? parametrization on the Class to ensure this?

另外,我发现可能存在可能的内存泄漏。我不确定我完全理解这是怎么发生的。我只会将单个对象粘贴到地图中,那么是否仍会出现内存泄漏问题?如果是这样,我该如何阻止呢?

Also, I found there could be a possible memory leak when doing something like this. I'm not sure I fully understand how this happens. I will only be sticking singleton objects into the map, so would there still be concern for a memory leak? If so, how do I prevent it?

推荐答案

Java的类型系统根本不足以强制执行类型约束你是直接描述,你需要做一些不安全的强制转换才能使其工作 - 或者将 Map 包装在其他强制类型安全的API中。 番石榴 ClassToInstanceMap 仅针对此用例执行此操作,提供了外部安全的API对 Map 接口施加额外限制以使其工作。 (披露:我向Guava捐款。)

Java's type system is simply not strong enough to enforce the type constraint you're describing directly, and you'll need to do some unsafe casts to make this work -- or wrap the Map in some other API that enforces the type safety. Guava's ClassToInstanceMap does just that for exactly this use case, providing an externally safe API that imposes additional restrictions on the Map interface to make it work. (Disclosure: I contribute to Guava.)

这是唯一一次导致内存泄漏的情况是,如果你在这里使用的某些类不会被保留用于申请的生命。对于许多用户来说,这不是一个问题,特别是如果您正在编写一个服务器端应用程序而不关心卸载未使用的类。

The only time this can cause a memory leak is if there's some classes you're using here that would not be retained for the life of the application. This isn't a concern for many users, especially if you're writing a "server side" application that isn't as concerned about unloading unused classes.

这篇关于Java map,key = class,value =该类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆