19

I am curious how to make this work

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

That obviously doesn't work. I would want something like this

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

but this seems like not a valid java sytax.

How can make this work?

EDIT: The reason I want this is because I have a method like this

   protected <ConfigType> ConfigValue<ConfigType> getSectionConfig(String name, Class<ConfigType> configType) {
        return config.getConfig(name);
    }

I would like to call this as so

ConfigValue<Map<String,Object>> config = getSectionConfig("blah", Map<String,Object>.class>);
Map<String,Value> val = config.value();
Surya
  • 4,922
  • 8
  • 41
  • 54
  • 3
    Why would you want this? – Luiggi Mendoza Nov 15 '13 at 21:22
  • 2
    `Map.class` can't exist. A `Type` that describes that signature can though, and you can use a [super type token](http://gafter.blogspot.sk/2006/12/super-type-tokens.html) to get that type, but `Type`s don't have the reflection capabilities of a `Class`. – millimoose Nov 15 '13 at 21:23
  • How make it work or how make it joke? –  Nov 15 '13 at 21:27
  • @LuiggiMendoza updated my question with use case. – Surya Nov 15 '13 at 21:31
  • @nikpon what joke? I dont get what your comment means, – Surya Nov 15 '13 at 21:38
  • Have you added the class parameter to `getSectionConfig` merely because you want to indicate the return type to the compiler? Do you realize that there will be casting somewhere, probably in the implementation of `getSectionConfig` or its dependencies, because you can't implement a dynamically-typed map in static fashion? – Judge Mental Nov 15 '13 at 22:14
  • 1
    @JudgeMental Yes but I want to limit casting to just one place. Not all over my code. – Surya Nov 16 '13 at 17:57

2 Answers2

19

Do a brute cast

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

this is not theoretically correct, but it is not our fault. We need such hacks some times.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61
4

According to the JLS, Section 15.8.2, you can't do that, because:

The type of C.class, where C is the name of a class, interface, or array type (§4.3), is Class<C>.

The closest you can come is

Class<Map> food = Map.class;
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • That is what I have currently but its not entirely typesafe and I have to do casting. :-\ – Surya Nov 15 '13 at 21:32