Search code examples
javaenumsjavabeansopencsv

OpenCSV - register custom converter


So I'm using opencsv to convert a csv to beans. This all works fine with primitive values, but I want to use enums and this is giving some issues.

I'm going through the code, and it seems I need to completely implement a new mappingstrategy to do this just to set a custom convertor. Is there a better way for this?

Current code for the conversion:

CsvToBean<MyType> csvBean = new CsvToBeanBuilder<MyType>(new FileReader(csvFile))
                 .withType(MyType.class)
                 .withIgnoreLeadingWhiteSpace(true)
                 .withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_QUOTES)
                 .build();

I found some questions from 2012 in regards to this, but the answers are no longer applicable for the current opencsv version (4.2).


Solution

  • Ok it turns out there's a @CsvCustomBindByName(column = 'foo', converter = Bar.class)

    Annotation that does exactly what I want. This class just needs to be of type <T> extends AbstractBeanField<T>