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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How can I create this custom Bottom Navigation on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
You can use @IntDef or @StringDef annotations for your methods like this:
To use ints as is done with the Toast class, you can do something like this:
VALUE_ONE
andVALUE_TWO
are static and final, meaning that throughout the entire application there will only be one instance of that variable, and its value will never change (if you know C, it is similar to a#DEFINE
). Thus, when someone passesMyClass.VALUE_ONE
as an argument, you know exactly what it is, every time, while the caller doesn't necessarily need to know the integer value behind the constant. And then you will want to do a runtime check to make sure that what was passed in was one of the valid values, and if not, throw an exception. Or, if the value passed in isn't very critical, you could just set a default value if the argument is incorrect rather than throw an exception.Use an Enum Type, from the Java Tutorial,
As an 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,