Search code examples
javasupercsv

Super CSV: Looking for integer equivalent to LMinMax


With supercsv, I can apply minimum and maximum constraints to a long column using LMinMax(), but how can I do that with a column that maps to an integer? If I use LMinMax on a column that maps to an integer in my bean, when I try to read the file in I get a org.supercsv.exception.SuperCsvReflectionException because it is looking for a setter that takes a long rather than an integer.


Solution

  • The only cell processor combination that would work is something like

    new LMinMax(0, 10, new FmtNumber("###", new ParseInt()))
    

    which is horrible.

    The issue is that Super CSV's ReflectionUtils only allows for exact matches on type (autoboxing is supported though). You could raise a feature request on Github to get this fixed.

    You can work around this by using CsvDozerBeanReader (Dozer supports mapping from Long to Integer quite happily), or you could define your own custom cell processor as shown below.

    public class IntMinMax extends LMinMax {
    
        public IntMinMax(int min, int max) {
            super(min, max);
        }
    
        @Override
        public Object execute(Object value, CsvContext context) {
            Long result = (Long) super.execute(value, context);
            return result.intValue();
        }
    
    }
    

    This should work, but note that it doesn't allow processors being chained after it (the call to super.execute() reuses the min/max validation, but also means you can't stop it passing the Long to the next processor, so I just disabled chaining).