Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java map, key = class, value = instance of that 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?

like image 800
dnc253 Avatar asked Apr 17 '12 16:04

dnc253


People also ask

How do you check if a map contains a specific value in Java?

HashMap containsValue() Method in Java HashMap. containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map.

How does Java find the values with a given key in a map?

HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Can we use any class as map key in Java?

From Java 8 - Permgen was removed. Do you think it is ok to use Class instance as HashMap key in any situations? Be aware that you will still have a memory leak. Any dynamicly loaded class used in your HashMap (key or value) and (at least) other dynamically loaded classes will be kept reachable.


1 Answers

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.

like image 92
Louis Wasserman Avatar answered Sep 22 '22 15:09

Louis Wasserman