1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.