Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a Typed Class in Java? [duplicate]

Tags:

java

generics

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?

like image 373
Martin Avatar asked Oct 29 '15 10:10

Martin


2 Answers

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.

like image 127
Paul Boddington Avatar answered Oct 05 '22 19:10

Paul Boddington


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

like image 26
Tahar Bakir Avatar answered Oct 05 '22 19:10

Tahar Bakir