All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.beust.jcommander.converters.EnumConverter Maven / Gradle / Ivy

There is a newer version: 1.0.0-beta2
Show newest version
package com.beust.jcommander.converters;

import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;

import java.util.EnumSet;

/**
 * A converter to parse enums
 * @param  the enum type
 * @author simon04
 */
public class EnumConverter> implements IStringConverter {

  private final String optionName;
  private final Class clazz;

  /**
   * Constructs a new converter.
   * @param optionName the option name for error reporting
   * @param clazz the enum class
   */
  public EnumConverter(String optionName, Class clazz) {
    this.optionName = optionName;
    this.clazz = clazz;
  }

  @Override
  public T convert(String value) {
    try {
      try {
        return Enum.valueOf(clazz, value);
      } catch (IllegalArgumentException e) {
        return Enum.valueOf(clazz, value.toUpperCase());
      }
    } catch (Exception e) {
      throw new ParameterException("Invalid value for " + optionName + " parameter. Allowed values:" +
          EnumSet.allOf(clazz));

    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy