Can I have a wildcard on a map such as Map <Class <?>,?>

I have a private instance

private final Map<Class<?>, ?> map; 

This is syntactically correct. I want to do this.

 public class User { } public class UserSubclass extends User { } public class Role { } map.put(User.class, new User()); // valid map.put(User.class, new UserSubclass()); // valid map.put(Role.class, new Role()); // valid // But when I do the following I need to get an error map.put(User.class, new Role(); // invalid, compiler error 
  • How to declare a card?
  • How can I instantiate a HashMap object on this map?
+4
source share
2 answers

You cannot do this by default, but what you can do is create your own shared secure card that will work.

GenericMap will look like this:

 class GenericMap extends HashMap<Class<?>, Object> { public <T> T putClassAndInstance(Class<T> c, T o){ return c.cast(super.put(c, o)); } public <T> T getInstance(Class<T> c) { return c.cast(super.get(c)); } } 

And then you can use it like:

 GenericMap map = new GenericMap(); map.putClassAndInstance(User.class, new User()); // valid map.putClassAndInstance(User.class, new UserSubclass()); // valid map.putClassAndInstance(Role.class, new Role()); // valid map.putClassAndInstance(User.class, new Role()); // invalid, compiler error 

Thus, you do not need to create special methods for the user and role and still have the security of not adding the wrong object for the wrong type.

+4
source

No, simple java.util.Map does not support this. It is statically typed, and what you are asking for is basically dynamically typing one parameter based on the type of runtime of another.

However, the Guava class ClassToInstanceMap implements exactly what you want:

A map, each entry of which maps a Java source type to an instance of that type. In addition to the Map implementation, additional operations of the type putInstance(java.lang.Class<T>, T) and getInstance(java.lang.Class<T>) .

+5
source

All Articles