Java中的泛型方法返回参数
我有两种方法:Java中的泛型方法返回参数,java,class,generics,Java,Class,Generics,我有两种方法: private List<Song> toSongList(String json) { ObjectMapper mapper = new ObjectMapper(); List<Song> list = null; list = mapper.readValue(json, mapper.getTypeFactory() .constructCollectionType(List.cla
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;
}
私有列表到songlist(字符串json){
ObjectMapper mapper=新的ObjectMapper();
List=null;
list=mapper.readValue(json,mapper.getTypeFactory()
.ConstructionCollectionType(List.class、Song.class));
退货清单;
}
私有列表到InterpreterList(字符串json){
ObjectMapper mapper=新的ObjectMapper();
List=null;
list=mapper.readValue(json,mapper.getTypeFactory()
.ConstructionCollectionType(List.class、解释器.class));
退货清单;
}
我称之为:
List<Song>songs = toSongList(jsonS);
List<Interpreter>interpreter = toInterpreterList(jsonI);
Listsongs=toSongList(jsonS);
ListExplorer=toInterpreterList(jsonI);
但是我想要一个方法,我可以这样调用它:
List<Song>songs = toList(Song.class, jsonS);
List<Interpreter>interpreter = toList(Interpreter.class, jsonI);
Listsongs=toList(Song.class,jsonS);
ListExplorer=toList(explorer.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;
}
私有列表列表(类clazz,字符串json){
ObjectMapper mapper=新的ObjectMapper();
List List=mapper.readValue(json,mapper.getTypeFactory()
.ConstructionCollectionType(List.class,clazz));
退货清单;
}
使您的toList()方法参数化:私有列表toList(类klass,字符串json)
请参见.Btw,Song.class
而不是class.Song
。我猜您在最后两行中指的是Song.class和explorer.class。