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'
If you break down that type into its component parts you get:
?ClassClass<?>StringMapMap<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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With