user8297969
user8297969

Reputation: 455

How to avoid cast using Spring ConversionService with target type List<String>?

I have the following Spring converter:

@Component
public class MyObjectToStringList implements Converter<MyObject, List<String>>{

    @Override
    public List<String> convert(MyObject obj) {
        List<String> items = new ArrayList<>(
                Arrays.asList(
                        obj.get().split("\\r?\\n")));

        items.remove(0);

        return items;
    }

}

In another component, I use the converter via the conversion service:

@Component
@RequiredArgsConstructor
public class MyService {

    private final ConversionService conversionService;

    public List<String> get(MyObject obj) {

        @SuppressWarnings("unchecked")
        List<String> rows = (List<String>) conversionService.convert(obj, List.class);

This works but is there anyway to avoid the unchecked cast?

Upvotes: 1

Views: 674

Answers (1)

amseager
amseager

Reputation: 6391

You can change the target type to String[] and modify the converter like this:

@Component
public class MyObjectToStringList implements Converter<MyObject, String[]>{

    @Override
    public String[] convert(MyObject obj) {
        List<String> items = new ArrayList<>(
                Arrays.asList(
                        obj.get().split("\\r?\\n")));

        items.remove(0);

        return items.toArray(new String[0]);
    }

}

Then perform the conversion in this way:

List<String> rows = Arrays.asList(conversionService.convert(obj, String[].class));

P.S. Inspired by this answer: https://stackoverflow.com/a/11845385/5572007

Upvotes: 1

Related Questions