How to generate class character <?> Using javapoet

I want to create 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 a "class"

+4
source share
2 answers

If you break this type down into its component parts, you get:

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

You can then create these components in the same way using the JavaPoet API:

  • 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 this type, doing the same for HashMapshould be easy (just replace it Map.classwith HashMap.class), and then building the field can be done as usual.

FieldSpec.builder(mapStringClass, "ID_MAP")
    .addModifiers(PUBLIC, STATIC)
    .initializer("new $T()", hashMapStringClass)
    .build();
+7
source

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);
}

Import 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;

-

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<?>>();
}
+3

Source: https://habr.com/ru/post/1660305/


All Articles