HashMap for classes, not objects
I want to assign ui-Classes to a model-class each. By this I want to find the class where to store the date from the user interface. Please don't refer to the design but to my question on a HashMap
's usage ;-)
I am aware of the class HashMap
but only used it to assign objects to other objects.
How can I manage to link always two CLASSES with each other?
publi开发者_运维百科c static final HashMap<class,class> componentMap=new HashMap<class, class>();
componentMap.put(ToolPanel.class, ToolComponent.class);
The code above does not work...
You want a Map<Class<?>, Class<?>>
.
Class
here refers to java.lang.Class
, which is a generified type. Unless you have more specific bounds, the unbounded wildcard <?>
can be used (see Effective Java 2nd Edition, Item 23: Don't use raw types in new code)
Note that the interface Map
is used here instead of a specific implementation HashMap
(see Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces).
Note that Map<Class<?>, Class<?>>
still maps objects, but the type of those objects are now Class<?>
. They are still objects nonetheless.
See also
- Java Tutorial/Generics (original dead link from Archive.org)
- Angelika Langer's Java Generics FAQ
- JLS 15.8.2 Class Literals
A class literal is an expression consisting of the name of a
class
[...] followed by a.
and the tokenclass
. The type of a class literal,C.class
, whereC
is the name of aclass
[...] isClass<C>
.
Related questions
- What is a raw type and why shouldn't we use it?
Imposing restrictions with bounded wilcards
Here's an example of imposing bounded wildcards to have a Map
whose keys must be Class<? extends Number>
, and values can be any Class<?>
.
Map<Class<? extends Number>, Class<?>> map
= new HashMap<Class<? extends Number>, Class<?>>();
map.put(Integer.class, String.class); // OK!
map.put(Long.class, StringBuilder.class); // OK!
map.put(String.class, Boolean.class); // NOT OK!
// Compilation error:
// The method put(Class<? extends Number>, Class<?>)
// in the type Map<Class<? extends Number>,Class<?>>
// is not applicable for the arguments (Class<String>, Class<Boolean>)
As you can see, the generic compile-time typesafety mechanism will prevent String.class
from being used as a key, since String
does not extends Number
.
See also
- Java Tutorials/Generics/More Fun with Wildcards
- Angelika Langer's Java Generics FAQ/What is a bounded wildcard?
It should have been:
HashMap<Class,Class>
(capital C)
or better:
HashMap<Class<?>,Class<?>>
The declaration should be:
public static final HashMap<Class<?>, Class<?>> componentMap = new HashMap<Class<?>, Class<?>>();
精彩评论