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
To use ints as is done with the Toast class, you can do something like this:
public class MyClass {
//by convention, constant names are all caps
public static final int VALUE_ONE = 0;
public static final int VALUE_TWO = 1;
public void myMethod(int value) throws InvalidParameterException {
if(value != VALUE_ONE || value != VALUE_TWO) {
throw new InvalidParameterException();
//or set default value instead of throwing an exception
}
else {
//your code
}
}
}
VALUE_ONE
and VALUE_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 passes MyClass.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.