我有一种方法在我使用实际类时工作正常,但在使用泛型时没有给出预期的输出。
下面是使用 ABC 类时工作正常的方法
public static List<ABC> getMemberViewRepresentation(Response response) throws JSONException, IOException {
JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
ObjectMapper mapper = new ObjectMapper();
JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
TypeReference<HashMap<String, ABC>> typeRef = new TypeReference<HashMap<String, ABC>>() {};
Map<String, ABC> map = mapper.readValue(memberViewObj.toString(), typeRef);
return new ArrayList<>(map.values());
}
此方法给出了正确的输出,其中包含 ABC 类型的列表。
但我想编写动态传递类的代码,以便任何人都可以使用此方法。所以我写了下面的代码,我也尝试了其他方法,但似乎都不起作用。
public static<T> List<T> getMemberViewRepresentation(Response response) throws JSONException, IOException {
JSONObject jsonObj = new JSONObject(response.readEntity(String.class));
ObjectMapper mapper = new ObjectMapper();
JSONObject memberViewObj = (JSONObject)jsonObj.get("members");
TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {};
Map<String, T> map = mapper.readValue(memberViewObj.toString(), typeRef);
return new ArrayList<>(map.values());
}
I am calling in this way
List<ABC> nodes = ResponseUtil.getMemberViewRepresentation(response);
但是上述方法的输出是不一样的。列表不是 ABC 类型
@JsonIgnoreProperties(ignoreUnknown = true)
public class ABC {
@JsonProperty("id")
private int id;
@JsonProperty("uid")
private String uid;
public int getId() {
return id;
}
public String getUid() {
return uid;
}
}
知道如何保持方法动态以便我可以单独传递类详细信息
最佳答案
我想,你需要的是:
List<ABC> nodes = ResponseUtil.<ABC>getMemberViewRepresentation(response);
...将通用参数推断为静态方法(没有类型化参数)。
注意额外的<ABC>
在方法调用之前!
通常你不需要它,因为常规的泛型方法是这样的:
public static<T> void foo(T someInput) {...}
...并提供 someInput
, T
在运行时已知/易于推断。在你的情况下 Response
与ABC
无关...因此无法推断(除了 ?
之外的任何其他内容)。
第一个方法按预期工作,因为没有“泛型方法”,而“类泛型类型”似乎被正确推断(在您的代码/配置中的其他地方)。
第二个没有,因为缺少“通用方法类型”(我假设分别推断为 <?>
<java.lang.Object>
...所以你得到一个 List<Object>
返回并分配给你的 List<ABC>
,这不是预期的那样,但至少是“无故障”)。
你可以争论,我们可以“推断”ABC
从返回类型(你期望一个 List<ABC>
,其中交付了一个 List<T>
),但不幸的是这不是它的工作方式/此信息此时不可用/需要更深入的研究。
关于Java Generic Map 未在运行时转换为正确的类型以进行 Json 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888228/