所以我有这两种方法:
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/