1 package com.opencsv.bean;
2
3 import com.opencsv.ICSVParser;
4 import com.opencsv.exceptions.CsvDataTypeMismatchException;
5 import org.apache.commons.lang3.EnumUtils;
6 import org.apache.commons.lang3.StringUtils;
7
8 import java.util.Locale;
9 import java.util.ResourceBundle;
10
11
12
13
14
15
16
17
18
19
20 public class ConverterEnum extends AbstractCsvConverter {
21
22
23
24
25
26
27
28
29
30 public ConverterEnum(Class<?> type, String locale, String writeLocale, Locale errorLocale) {
31 super(type, locale, writeLocale, errorLocale);
32 }
33
34 @Override
35 @SuppressWarnings("unchecked")
36 public Object convertToRead(String value) throws CsvDataTypeMismatchException {
37 Object o = null;
38 if (StringUtils.isNotEmpty(value)) {
39 o = EnumUtils.getEnumIgnoreCase((Class<Enum>)type, value);
40 if(o==null) {
41 throw new CsvDataTypeMismatchException(value, type, String.format(
42 ResourceBundle.getBundle(ICSVParser.DEFAULT_BUNDLE_NAME, this.errorLocale).getString("illegal.enum.value"),
43 value, type.getName()));
44 }
45 }
46 return o;
47 }
48
49 @Override
50 public String convertToWrite(Object value) {
51 String s = StringUtils.EMPTY;
52 if(value != null) {
53 Enum e = (Enum)value;
54 s = e.name();
55 }
56 return s;
57 }
58 }