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?
You can hide the collection and only allow it to be accessed via accessor methods.
The warning can be ignored as you know the cast in the last method is safe even if the compiler does not.
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'sClassToInstanceMap
does just that for exactly this use case, providing an externally safe API that imposes additional restrictions on theMap
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.
This isn't possible due to type erasure.
However, you could subclass
HashMap
and write some logic into theput
method which will do this for you:(Code for illustrative purposes only)
I had the same requirement. I solved it using the below code :
What you are using is a heterogeneous container. These can be made typesafe by using type tokens (as you already do) and
Class.cast()
with the correct application logic: So there is an unchecked suppressWarning withinClass.cast()
, but the application logic guarantees correctness.I advise you read Josh Bloch's Effective Java Item 29: Consider typesafe heterogeneous containers. His example is:
I only see a possibility for memory leakage if you hold arbitrarily many different types you actually no longer need.