8

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?

Martin
  • 3,018
  • 1
  • 26
  • 45
  • 2
    Could you provide some insight on what are you trying to achieve? – alexk Oct 29 '15 at 10:28
  • @alexk, I have a situation where I am invoking a method that receives a `Class` as a parameter. In my case, it would be the `Class`. If I write `Map.class`, it works fine, but I dislike the warning... I'm looking for a way to get rid of the warning (not using `@SupressWarnings`). – Martin Oct 29 '15 at 14:00

3 Answers3

5

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.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
2
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

Tahar Bakir
  • 716
  • 5
  • 14
0
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

KristofMols
  • 3,487
  • 2
  • 38
  • 48
morels
  • 2,095
  • 17
  • 24
  • 1
    `class` is a reserved word in Java, you can't use it as a variable name – JonK Oct 29 '15 at 10:31
  • 3
    The OP needs a Class, not a Map. – Paul Boddington Oct 29 '15 at 10:31
  • @JonK right, I did not care the name of the variable. thx. – morels Oct 29 '15 at 10:32
  • 1
    @morels: I think here the OP has another problem. You can get a `Class` object from an interface. But here he has a typed Map, not a raw Map, so the compiler won't let him get a `Class` object. Sorry, but I'm downvoting until you edit your answer. – javatutorial Oct 29 '15 at 10:39
  • I don't think that's what the OP is looking for. OP wants a Class type and not an instance of a Map. – Avi Oct 29 '15 at 10:48