kaolick kaolick - 5 months ago 28x
Java Question

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

I want to write a method that only takes certain values for a parameter, like f.e. in the

class in Android. You can only use
as duration for the method
makeText(Context context, int resId, int duration)
. I had a look at the source code of the
class but found nothing there. How can I achieve that?


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 {

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


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;