How to only allow certain values as parameter for a method in Java?

android, android-toast, java, methods, parameters

Solution

Use an Enum Type, from the Java Tutorial,

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

As an example,

public enum MyEnum {
  ONE, TWO;
}

public static void myMethod(MyEnum a) {
  // a must be MyEnum.ONE or MyEnum.TWO (in this example)
}

Edit

To get String(s) from your enum types you can add field level values (which must be compile time constants) with something like,

public enum MyEnum {
  ONE("uno"), TWO("dos");
  MyEnum(String v) {
    value = v;
  }
  private String value;
  public String getValue() {
    return value;
  }
}

Problem

I want to write a method that only takes certain values for a parameter, like f.e. in the `Toast` class in Android. You can only use `Toast.LENGTH_SHORT` or `Toast.LENGTH_LONG` as duration for the method `makeText(Context context, int resId, int duration)`. I had a look at the source code of the `Toast` class but found nothing there. How can I achieve that?

Original source