我想编写一个通用函数来解析json字符串(代码下面的stringEtcdContent)。该字符串具有键为“值”的对象列表。我将json解析到树中,获取JsonNode的列表(下面的valueNodes)以及使用通用类解析的字符串。我具有该功能的类是:“公共抽象类DashboardReportProvider”。基于此处的类似问题,我编写了此函数:
@SuppressWarnings("unchecked")
public List<T> getStatusList(String path) {
Class<T> clazz;
clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
List<T> statusList = new ArrayList<>();
T statusItem;
ObjectMapper mapper = new ObjectMapper();
try {
String stringEtcdContent = etcdCommandExecutor.getEtcdValue(path);
JsonParser parser=new MappingJsonFactory().createParser(stringEtcdContent);
JsonNode rootNode=parser.readValueAsTree();
List<JsonNode> valueNodes=rootNode.findValues("value");
Iterator<JsonNode> valueNodesIterator=valueNodes.listIterator();
while (valueNodesIterator.hasNext()) {
JsonNode valueNode=(JsonNode)valueNodesIterator.next();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
String valueString = writer.writeValueAsString(valueNode);
statusItem = mapper.readValue(valueString, clazz);
statusList.add(statusItem);
}
return statusList;
} catch (Exception e) {
LOG.error(e.getMessage());
}
return statusList;
}
它可以正常编译,但是当我尝试运行代码时,出现以下错误: “ [ERROR] java.lang.Class无法转换为java.lang.reflect.ParameterizedType”。怎么了?
答案 0 :(得分:0)
尝试ObjectMapper,
const A = {x: 0, y: 0};
const B = {x: 10, y: 0};
const direction = 90;
const width = 10;
const halfWidth = width / 2;
// tried the following one that I found but
// no lock, I assume somethings off with angles
function getCorner(point, angle, length) {
return {
x: point.x + Math.cos(angle) * length,
y: point.y + Math.sin(angle) * length
};
}
// EXPECTED
// bottom left: {x: 0, y: 5}
// bottom right: {x: 0, y: -5}
// top left: {x: 10, y: 5}
// top right: {x: 10, y: -5}
console.log(
"bottom left:",
getCorner(A, direction - 90, halfWidth)
);
console.log(
"bottom right:",
getCorner(A, direction + 90, halfWidth)
);
console.log("---");
console.log(
"top left:",
getCorner(B, direction - 90, halfWidth)
);
console.log(
"top right:",
getCorner(B, direction + 90, halfWidth)
);
其中Object.class-强制转换为类型