20

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();
7
  • 3
    Why would you want this? Commented Nov 15, 2013 at 21:22
  • 2
    Map<String,String>.class can't exist. A Type that describes that signature can though, and you can use a super type token to get that type, but Types don't have the reflection capabilities of a Class. Commented Nov 15, 2013 at 21:23
  • How make it work or how make it joke? Commented Nov 15, 2013 at 21:27
  • @LuiggiMendoza updated my question with use case. Commented Nov 15, 2013 at 21:31
  • 1
    @JudgeMental Yes but I want to limit casting to just one place. Not all over my code. Commented Nov 16, 2013 at 17:57

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

1 Comment

That is what I have currently but its not entirely typesafe and I have to do casting. :-\
0

Not sure but may be ParameterizedTypeReference class can help you?

private static final ParameterizedTypeReference<Map<String, Object>> YOUR_TYPE_NAME = new ParameterizedTypeReference<Map<String, Object>>() {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.