I need to declare an instance of Map.class
, but the Map is typed... So I need something like this:
Class <Map<String, String>> clazz = Map.class;
This line causes a compile error. What is the clean way of expressing this?
I need to declare an instance of Map.class
, but the Map is typed... So I need something like this:
Class <Map<String, String>> clazz = Map.class;
This line causes a compile error. What is the clean way of expressing this?
You can do it with casts.
Class<Map<String, String>> clazz = (Class<Map<String, String>>) (Object) Map.class;
This generates a warning but compiles.
The problem with it is that due to type erasure, the resulting object at runtime is no different from Map.class
(it doesn't know about the type).
If you need an object that truly represents Map<String, String>
you can look into using java.lang.reflect.Type
or Guava's TypeToken
.
import java.util.*;
public class Test{
public static void main(String [] args){
Class <Map> clazz = Map.class;
System.out.println(clazz);
}
}
will print
interface java.util.Map
Map<String, String> clazz = new HashMap<String, String>()
Remember that Map is an interface, not instantiable directly but only via a class implementing it, like HashMap
or TreeMap