Search code examples
javagenericscasting

Java generics: Declare map value of generic type


I am new to generics.

Having a Map like

private static Map<String, Object> map;

and a method like

public <T> T getObject(final Class<T> myClass) {
    return (T)map.get(myClass);
}

How to change the map declaration in order to not have to do the cast when returning from the method ?


Solution

  • You would need to make a generic class, not a generic method:

    public class MyClass<T> {
       private Map<String, T> map;
    
       public T getObject(final String key) {
        return map.get(key);
       }
    }
    

    Also, I changed the parameter from a Class to a String. It doesn't make sense to pass a Class if map.get() expects a String.

    Edit: I didn't notice that map was static. If you can change it to non-static without it breaking other parts of your program, this could work. If you can't, then you cannot avoid a cast.