Search code examples
javaspring-bootgenericsobjectmapper

Is there a way to cast List Object into exact List Class in an generic function?


I am coding in an Spring Boot Project and there was a lot of API with diffrent Request Param so I'm trying to write a generic function with mapper an request param into a list object, then cast it into a class like the code below

    public static <D> List<D> convertStringListToObject(String string) {
        if (string == null) return null;
        try {
            return objectMapper.readValue(string, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

But the result is it can only return a list of Object not the list of D class like I'm expected. Does anyone have any ideas how to write this function?

Eddited: Here is how I invoke it:

filterBlockRequestDto.setPopularFiltersList(ApiUtil.convertStringListToObject(filterBlockRequestDto.getPopularFilters()));

The FilterBlockRequestDto class

import lombok.*;

import java.util.List;

@Getter
@Setter
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class FilterBlockRequestDto {
    Integer locationId;
    Integer projectId;
    String totalBudget;
    List<TotalBudgetDto> totalBudgetList;
    // The string was pass in Request param
    String popularFilters;
    List<PopularFiltersDto> popularFiltersList;
    Integer viewRating;
    Integer numberOfBed;
}


Solution

  • One way is to accept type reference as parameter so that the caller can provide the target class and as TypeReference is a subclass, generic type information will be available at runtime.

        public static <D> List<D> convertStringListToObject(String string, TypeReference<List<D>> typeReference) {
            if (string == null) return null;
            try {
                return objectMapper.readValue(string, typeReference);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }