gpt4 book ai didi

java - Java 中的泛型方法返回参数

转载 作者:行者123 更新时间:2023-11-29 05:07:05 25 4
gpt4 key购买 nike

所以我有这两种方法:

private List<Song> toSongList(String json) {
ObjectMapper mapper = new ObjectMapper();
List<Song> list = null;
list = mapper.readValue(json, mapper.getTypeFactory()
.constructCollectionType(List.class, Song.class));
return list;
}

private List<Interpreter> toInterpreterList(String json) {
ObjectMapper mapper = new ObjectMapper();
List<Interpreter> list = null;
list = mapper.readValue(json, mapper.getTypeFactory()
.constructCollectionType(List.class, Interpreter.class));
return list;
}

我调用:

List<Song>songs = toSongList(jsonS);
List<Interpreter>interpreter = toInterpreterList(jsonI);

但是我想要一个单一的方法,我可以这样调用它:

List<Song>songs = toList(Song.class, jsonS);
List<Interpreter>interpreter = toList(Interpreter.class, jsonI);

我怎样才能做到这一点?

最佳答案

这应该有效:

private <T> List<T> toList(Class<T> clazz, String json) {
ObjectMapper mapper = new ObjectMapper();
List<T> list = mapper.readValue(json, mapper.getTypeFactory()
.constructCollectionType(List.class, clazz));
return list;
}

关于java - Java 中的泛型方法返回参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com