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

Variables scope which are defined within a while block in stored procedures - SQl Server

sql-server sql-server-2008 variables scope declaration

I've come across a interesting scenario (at least for me) in a stored procedure. Would like to have experts opinion and thoughts on it.

Querying list items and using SharePoint web services vs the object model

performance web-services sharepoint

My company is looking into writing a custom application that will need to perform many list item queries across multiple site collections. It will need to run for WSS 3.0 and it 'would be nice' if it

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.