problem with using java reflection
Suppose I want to write a function, which will create a HashMap from some specified type T to String, for example, a HashMap from Integer to String as follows:
HashMap<Integer, String> myHashMay = new HashMap<Integer, String>()
;
I want to have flexibilty to specify the type T. So I write a function as:
void foo(Class<?> myClass) {
HashMap<myClass, String> myHashMay = new HashMap<myClass, String>();
.......
}
so that if I invoke foo(Integer.class), a HashMap from Integer to String will be created inside this function. Apparently the above foo function does not even compile. Could anybody give me some hints on how to write such a function correctly with the given function signature.
Th开发者_开发百科anks,
<T> void foo(Class<T> myClass) {
HashMap<T, String> myHashMay = new HashMap<T, String>();
...
}
EDIT: However, method with such a signature doesn't seem to be very useful, because T is used only for type checking at compile time. I can imagine only the single scenario when it can be used:
<T> void foo(Class<T> myClass) {
HashMap<T, String> myHashMay = new HashMap<T, String>();
...
try {
T key = myClass.newInstance();
myHashMay.put(key, "Value");
} catch (Exception ex) { ... }
...
}
This function creates a map like you are trying to do:
public <KeyType> Map<KeyType,String> createMapWithKeyType(Class<KeyType> keyType)
{
return new HashMap<KeyType, String>();
}
Note: pay attention to the comment by matt b, he makes a good point.
精彩评论