javagenericsraw-types

Map is a raw type when assigning Map.class. But assigning a type results in a mismatch. How do I parameterize Map.class?


I receive a warning here that Map is a raw type.

// Map is a raw type. References to generic type Map<K,V> should be parameterized
Class<Map> c = Map.class;

But if I parameterize the type, then I get a mismatch:

// Type mismatch: cannot convert from Class<Map> to Class<Map<Object,Object>>
Class<Map<Object, Object>> c = Map.class;

I have tried a few variations, but I can't find any way to parameterize the right side of the expression (Map.class) to satisfy the left side, which is parameterized.

How do I parameterize Map.class in this instance?

In this case I am passing it to a method with a signature:

public <T> T method(Class<T> type) {
   return (T) otherMethod(type);
}

I only want to provide the Map type, as I don't know what kind of map is used internally, and this detail is not important. I am trying to resolve the warning I get when calling the method:

// Type safety: The expression of type Map needs unchecked conversion to conform to Map<String,Object>
Map<String, Object> a = method(Map.class);

Solution

  • This suppresses the warning at the call site:

    public static <T> T method(Class<? super T> type) {
        return (T) otherMethod(type);
    }
    

    There is still an unchecked cast warning on the expression (T) otherMethod(type), but I believe that is unavoidable.