Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate symbol Class<?> with javapoet

Tags:

javapoet

i want to generate a field like this:

public static Map<String, Class<?>> ID_MAP = new HashMap<String, Class<?>>();

WildcardTypeName.subtypeOf(Object.class) can give '?' WildcardTypeName.subtypeOf(Class.class) can give 'Class'

like image 722
dong sheng Avatar asked Nov 09 '16 14:11

dong sheng


1 Answers

If you break down that type into its component parts you get:

  • ?
  • Class
  • Class<?>
  • String
  • Map
  • Map<String, Class<?>>

You can then build up these component parts in the same way using JavaPoet's APIs:

  • TypeName wildcard = WildcardTypeName.subtypeOf(Object.class);
  • TypeName cls = ClassName.get(Class.class);
  • TypeName clsWildcard = ParameterizedTypeName.create(cls, wildcard);
  • TypeName string = ClassName.get(String.class);
  • TypeName map = ClassName.get(Map.class);
  • TypeName mapStringClass = ParameterizedTypeName.create(map, string, clsWildcard);

Once you have that type, doing the same for HashMap should be easy (just replace Map.class with HashMap.class) and then building the field can be done like normal.

FieldSpec.builder(mapStringClass, "ID_MAP")
    .addModifiers(PUBLIC, STATIC)
    .initializer("new $T()", hashMapStringClass)
    .build();
like image 66
Jake Wharton Avatar answered Sep 21 '22 13:09

Jake Wharton