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:
?
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();
Using ParameterizedTypeName.get()
worked for me -
public static void main(String[] args) throws IOException {
TypeName wildcard = WildcardTypeName.subtypeOf(Object.class);
TypeName classOfAny = ParameterizedTypeName.get(
ClassName.get(Class.class), wildcard);
TypeName string = ClassName.get(String.class);
TypeName mapOfStringAndClassOfAny = ParameterizedTypeName.get(ClassName.get(Map.class), string, classOfAny);
TypeName hashMapOfStringAndClassOfAny = ParameterizedTypeName.get(ClassName.get(HashMap.class), string, classOfAny);
FieldSpec fieldSpec = FieldSpec.builder(mapOfStringAndClassOfAny, "ID_MAP")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.initializer("new $T()", hashMapOfStringAndClassOfAny)
.build();
TypeSpec fieldImpl = TypeSpec.classBuilder("FieldImpl")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addField(fieldSpec)
.build();
JavaFile javaFile = JavaFile.builder("com", fieldImpl)
.build();
javaFile.writeTo(System.out);
}
Imports used by me -
import com.squareup.javapoet.*;
import javax.lang.model.element.Modifier;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
This generates the output as -
package com; import java.lang.Class; import java.lang.String; import java.util.HashMap; import java.util.Map; public final class FieldImpl { public static Map<String, Class<?>> ID_MAP = new HashMap<String, Class<?>>(); }
来源:https://stackoverflow.com/questions/40509818/how-to-generate-symbol-class-with-javapoet