java map class,Java map,key = class,value =该类的实例

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, Object> myMap = new HashMap, 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'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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值