Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generics: getting class of a class with generic parameters

Tags:

java

generics

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();
like image 582
Surya Avatar asked Nov 15 '13 21:11

Surya


People also ask

Can a generic class have multiple generic parameters Java?

A Generic class can have muliple type parameters.

Can a generic class be derived from another generic class?

In the same way, you can derive a generic class from another generic class that derived from a generic interface. You may be tempted to derive just any type of class from it. One of the features of generics is that you can create a class that must implement the functionality of a certain abstract class of your choice.

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.


1 Answers

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.

like image 64
ZhongYu Avatar answered Nov 06 '22 01:11

ZhongYu