how to generate symbol Class<?> with javapoet

后端 未结 2 1011
轮回少年
轮回少年 2021-01-02 18:00

i want to generate a field like this:

public static Map> ID_MAP = new HashMap>();

相关标签:
2条回答
  • 2021-01-02 18:08

    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();
    
    0 讨论(0)
  • 2021-01-02 18:28

    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<?>>();
    }
    
    0 讨论(0)
提交回复
热议问题