How to declare a typed class in Java?

I need to declare an instance of Map.class , but the map is typed ... I need something like this:

 Class <Map<String, String>> clazz = Map.class; 

This line causes a compilation error. What is the clean way to express it?

+8
java generics
source share
3 answers

You can do this with the butt.

 Class<Map<String, String>> clazz = (Class<Map<String, String>>) (Object) Map.class; 

This generates a warning, but compiles.

The problem is that due to the erasure of the type, the resulting object at run time is no different from Map.class (it does not know about the type).

If you need an object that really represents Map<String, String> , you can examine java.lang.reflect.Type or Guava TypeToken .

+4
source share
 import java.util.*; public class Test{ public static void main(String [] args){ Class <Map> clazz = Map.class; System.out.println(clazz); } } 

will print

java.util.Map interface

+2
source share
 Map<String, String> clazz = new HashMap<String, String>() 

Remember that Map is an interface, not an immediate one, but only through a class that implements it, such as HashMap or TreeMap

0
source share

All Articles