1

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.

Thanks,

1
  • 1
    I feel compelled to note that if you instantiate an Object with reflection, there is no type information at compile-time so you'll have to do an unchecked cast anyway. in other words you can't instantiate a HashMap<Integer, String> with reflection, just a HashMap. Commented Jan 21, 2010 at 0:17

2 Answers 2

2
<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) { ... }
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thank you guys for both the answers and comments. They are very helpful. Since I am using some third party code, I have to hack this way in order to get my code work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.