Javapoet-带有嵌套参数tytypename的参数化typename



我如何创建以下:

HashMap<String, Pair<Boolean, Object>> mHashMap = new HashMap();

我有以下内容:

ParameterizedTypeName subType = ParameterizedTypeName.get(Pair.class, Boolean.class, Object.class);
ParameterizedTypeName mainType = ParameterizedTypeName.get(HashMap.class, String.class, Pair.class);
 builder.addField(
            FieldSpec.builder(mainType, "mHashMap", Modifier.PRIVATE, Modifier.FINAL)
                    .initializer("new HashMap<>()")
                    .build()
    );

现在如何将subTypemainType结合以获取正确的mainType

我需要以下内容:

ParameterizedTypeName mainType = ParameterizedTypeName.get(HashMap.class, String.class, subType);

类似的东西应该有效:

ParameterizedTypeName subType = ParameterizedTypeName.get(Pair.class, 
                                                          Boolean.class,
                                                          Object.class);
ClassName string = ClassName.get("java.lang", 
                                 "String");
ClassName hashMap = ClassName.get("java.util", 
                                  "HashMap");
ParameterizedTypeName mainType = ParameterizedTypeName.get(hashMap, 
                                                           string,
                                                           subType);
FieldSpec.builder(mainType, 
                  "mHashMap",
                  Modifier.PRIVATE,
                  Modifier.FINAL)
         .initializer("new HashMap<>()")
         .build();

上面的代码应生成:

private final HashMap<String, Pair<Boolean, Object>> mHashMap = new HashMap<>();

希望会有所帮助。

相关内容

  • 没有找到相关文章

最新更新