blob: 3e850bbd1de7b27c69b3df6b9f6958ccb1d0bc31 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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 <T> the enum type
* @author simon04
*/
public class EnumConverter<T extends Enum<T>> implements IStringConverter<T> {
private final String optionName;
private final Class<T> clazz;
/**
* Constructs a new converter.
* @param optionName the option name for error reporting
* @param clazz the enum class
*/
public EnumConverter(String optionName, Class<T> 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));
}
}
}
|