如何只允许某些值作为Java中方法的参数? [英] How to only allow certain values as parameter for a method in Java?

查看:74
本文介绍了如何只允许某些值作为Java中方法的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个只接受参数某些值的方法,例如f.e.在Android的Toast类中.您只能将Toast.LENGTH_SHORTToast.LENGTH_LONG用作方法makeText(Context context, int resId, int duration)的持续时间.我看了Toast类的源代码,但是什么都没找到.我该如何实现?

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?

推荐答案

使用

枚举类型是一种特殊的数据类型,它使变量成为一组预定义的常量.该变量必须等于为其预定义的值之一.常见示例包括指南针方向(北,南,东和西的值)和星期几.

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.

例如,

public enum MyEnum {
  ONE, TWO;
}

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

这篇关于如何只允许某些值作为Java中方法的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆