View Javadoc
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   * This class converts an input to an enumeration type and vice versa.
13   * The input string must match the enumeration value as declared, ignoring
14   * case. The output value will always be the enumeration value, exactly as
15   * declared.
16   *
17   * @author Andrew Rucker Jones
18   * @since 5.2
19   */
20  public class ConverterEnum extends AbstractCsvConverter {
21  
22      /**
23       * @param type    The class of the type of the data being processed
24       * @param locale   If not null or empty, specifies the locale used for
25       *                 converting locale-specific data types
26       * @param writeLocale   If not null or empty, specifies the locale used for
27       *                 converting locale-specific data types for writing
28       * @param errorLocale The locale to use for error messages.
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  }