When I pass a class as an argument and then I want to use it, it says can not be resolved to a type

1

I am creating a DAO class that what it does for now is to bring to memory lists of objects from a json file. This method receives the name of a class and with that it should bring me the list of objects of that class but when I want to tell it that it is a list of instances of that class it tells me that it can not be solved to a type. I leave the code that I have (use jackson):

public List getAll(Class className) {

    File json = new File(this.path);
    ObjectMapper mapper = new ObjectMapper();
    List<className> list = null;

    try
    {            
        list = mapper.readValue(json, new TypeReference<List<className>>() {});
    }
    catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}
    
asked by nmarchesotti 16.04.2018 в 18:58
source

1 answer

0

The code you provide does not compile, making some changes for it to compile, the code would look something like this:

public <T> List getAll(Class<T> className) {

    File json = new File(this.path);
    ObjectMapper mapper = new ObjectMapper();
    List<T> list = null;

    try {
        list = mapper.readValue(json, new TypeReference<List<T>>() {
        });

    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

But in the previous way, although it does not send an error, the contents of the returned list would not be objects of the appropriate type, but of LinkedHashMap .

Jackson needs additional information to be able to determine the parametric types, at runtime a List<Tipo> is the same as List<Object>

To return the appropriate type you can use:

public <T> List<T> getAll(Class<T> className) {
...
    list = mapper.readValue(json,
              mapper.getTypeFactory()
              .constructCollectionType(List.class, className));
...
}

And you would use it as:

List<Tipo> lista = getAll(Tipo.class);

Another option, using TypeReference , would be to pass the TypeReferece parameter built instead of trying to build it using generics:

public <T> T getAll(TypeReference<T> type) {
...
    return mapper.readValue(json, type);
...
}

But to use it, it's a bit more extensive:

List<Tipo> lista = getAll(new TypeReference<List<Tipo>>() {});
    
answered by 16.04.2018 / 20:19
source