这样强转编译器就报错:
Set<String> tables = (Set<String>) realMap.keySet()
改为对Set内具体元素强转则正常:
Set<Object> tables = realMap.keySet();
for(Object table: table){
String t= (String)table;
...
而把Object强转为带泛型的Map则不报错:
Map<String, OdpsPartitionInfoDTO> latestInfo = (Map<String, OdpsPartitionInfoDTO>) realMap.get(table);
附上源码,哪位大神解释下?
@Override
public CruiserItemResult.Rule doValidate(Map<String, String> ruleExpressionMap, Map<Object, Object> realMap) {
CruiserItemResult.Rule ruleResult = new CruiserItemResult.Rule();
ruleResult.setStatus(PASS);
String errMsg;
try {
if (realMap != null && !realMap.isEmpty()) {
for (Object table : realMap.keySet()) {
/* 上次巡检结果*/
String lastPartitionInfo = Diamond.getConfig((String) table, "ad_qa_base_platform", 10000L);
if (lastPartitionInfo != null && !lastPartitionInfo.isEmpty()) {
JSONObject lastJsonObject = JSON.parseObject(lastPartitionInfo);
if (realMap.containsKey(table)) {
Map<String, OdpsPartitionInfoDTO> latestInfo = (Map<String, OdpsPartitionInfoDTO>) realMap.get(table);
Map<String, OdpsPartitionInfoDTO> oldInfo = JSON.parseObject(lastJsonObject.getString((String) table), new TypeReference<Map<String, OdpsPartitionInfoDTO>>() {
});
if (oldInfo != null) {
for (Map.Entry<String, OdpsPartitionInfoDTO> old : oldInfo.entrySet()) {
if (latestInfo.containsKey(old.getKey()) &&
latestInfo.get(old.getKey()).getSize() != old.getValue().getSize()
&& old.getValue().getSize() > 0) {
errMsg = String.format("[%s][%s] 数据变化. O[%s], N[%s]", table, old.getKey(), old.getValue(), latestInfo.get(old.getKey()));
ruleResult.setStatus(FAIL);
ruleResult.setLevel(CRITICAL);
ruleResult.setMsg(errMsg);
logger.info(errMsg);
}
}
}
} else {
logger.info("本次巡检没有表: " + table);
}
}
Diamond.publishSingle((String) table, "ad_qa_base_platform", JSON.toJSONString(realMap.get(table)));
}
}
} catch (Exception e) {
errMsg = "校验失败. " + e.getMessage();
ruleResult.setStatus(FAIL);
ruleResult.setLevel(CRITICAL);
ruleResult.setMsg(errMsg);
e.printStackTrace();
}
return ruleResult;
}
本文探讨了Java中不同类型集合间的转换方法及可能引发的问题,特别是Set和Map类型的转换,并通过示例代码展示了如何避免类型转换错误导致的编译失败。

1058

被折叠的 条评论
为什么被折叠?



