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

前端 未结 3 2377
暖寄归人
暖寄归人 2021-02-20 02:03

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 o

3条回答
  •  Happy的楠姐
    2021-02-20 03:00

    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;
      }
    }
    

提交回复
热议问题