如何从给定的片段中返回 T.class?

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 出现错误,有人可以提出建议吗?


爪哇


POPMUISE
浏览 126回答 1
1回答

幕布斯7119047

不幸的是,您无法获得想要的东西。但是,您可以将Class<T>作为输入参数提交给yaml(...). 您还必须考虑文件名,因为它不再只是user.yaml.一个解决方案可能是将两者都作为参数传递private static <T> T yaml(final Class<T> clazz, final String fileName) throws IOException, JsonParseException, JsonMappingException {&nbsp; &nbsp; return MAPPER.readValue(new File(fileName), clazz);}我ObjectMapper从方法中删除了创建,因为它是线程安全的,因此可以存储为static final类字段。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java