how to generate symbol Class<?> with javapoet

泪湿孤枕 提交于 2019-11-30 20:33:14

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<?>>();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!