private static User yaml() throws IOException, JsonParseException, JsonMappingException { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); return mapper.readValue(new File("user.yaml"), User.class);}上面的代码特定于“用户”类我想让它像这样通用,private static <T> T yaml() throws IOException, JsonParseException, JsonMappingException { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); return mapper.readValue(new File("user.yaml"), T.class);}但是在 T.class 出现错误,有人可以提出建议吗?爪哇
1 回答

幕布斯7119047
TA贡献1794条经验 获得超8个赞
不幸的是,您无法获得想要的东西。但是,您可以将Class<T>作为输入参数提交给yaml(...). 您还必须考虑文件名,因为它不再只是user.yaml.
一个解决方案可能是将两者都作为参数传递
private static <T> T yaml(final Class<T> clazz, final String fileName) throws IOException, JsonParseException, JsonMappingException {
return MAPPER.readValue(new File(fileName), clazz);
}
我ObjectMapper从方法中删除了创建,因为它是线程安全的,因此可以存储为static final类字段。
添加回答
举报
0/150
提交
取消