Generic Method Return Parameter in Java

So I've got these 2 Methods:

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;
}

which I call with:

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

But I want to have a single Method, which I can call like this:

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

How can I achieve this?

Answers


This should work:

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;
}

Need Your Help

How to getElementByClass instead of GetElementById with JavaScript?

javascript class toggle getelementbyid getelementsbyclassname

I'm trying to toggle the visibility of certain DIV elements on a website depending on the class of each DIV. I'm using a basic JavaScript snippet to toggle them. The problem is that the script only...