aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/common/options/EnumConverter.java
blob: 2200f613044847f21d191b6e4c844eac259ee34e (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.common.options;

import java.util.Arrays;

/**
 * A converter superclass for converters that parse enums.
 *
 * <p>Just subclass this class, creating a zero argument constructor that
 * calls {@link #EnumConverter(Class, String)}.
 *
 * <p>This class compares the input string to the string returned by the toString()
 * method of each enum member in a case-insensitive way. Usually, this is the
 * name of the symbol, but beware if you override toString()!
 */
public abstract class EnumConverter<T extends Enum<T>>
    implements Converter<T> {

  private final Class<T> enumType;
  private final String typeName;

  /**
   * Creates a new enum converter. You *must* implement a zero-argument
   * constructor that delegates to this constructor, passing in the appropriate
   * parameters.
   *
   * @param enumType The type of your enumeration; usually a class literal
   *                 like MyEnum.class
   * @param typeName The intuitive name of your enumeration, for example, the
   *                 type name for CompilationMode might be "compilation mode".
   */
  protected EnumConverter(Class<T> enumType, String typeName) {
    this.enumType = enumType;
    this.typeName = typeName;
  }

  /**
   * Implements {@link #convert(String)}.
   */
  @Override
  public T convert(String input) throws OptionsParsingException {
    for (T value : enumType.getEnumConstants()) {
      if (value.toString().equalsIgnoreCase(input)) {
        return value;
      }
    }
    throw new OptionsParsingException("Not a valid " + typeName + ": '"
                                      + input + "' (should be "
                                      + getTypeDescription() + ")");
  }

  /**
   * Implements {@link #getTypeDescription()}.
   */
  @Override
  public final String getTypeDescription() {
    return Converters.joinEnglishList(
        Arrays.asList(enumType.getEnumConstants())).toLowerCase();
  }

}