3

如何创建以下内容:

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

1 回答 1

4

像这样的东西应该工作:

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

希望有帮助。

于 2018-02-11T14:50:11.373 回答