Java map, key = class, value = instance of the class

I don't know what I want to do is possible, but if so, I want to know how Basically, I want to create a map, where key is a class (Java. Lang. class), and the value of the entry is an instance of the class At present, I have

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

However, this means that any object can be placed in the map I want to do this if possible, so only one instance of a class in a key can be placed in the map Is there any way to use it? Parameterization ensures this on class?

In addition, I found that there may be a possible memory leak when doing such things I don't know. I fully understand what's going on I only paste single objects into the map, so I'm still worried about memory leakage? If so, how can I prevent it?

Solution

Java's type system is simply not powerful enough to enforce the type constraints you directly describe, and you need to perform some unsafe transformations to make it work - or wrap maps in other APIs that enforce type security Guava's classtoinstancemap only provides an external security API for this use case, imposing additional restrictions on the map interface to make it work (Disclosure: I contribute guava.)

The only time you can cause a memory leak is if some classes you use here will not be retained for the life of the application This is not a concern for many users, especially if you are writing a "server - side" application that doesn't care about uninstalling unused classes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>