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?
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
Java allows to pass null as an argument to set default values for optional parameters! Well, specifying null to indicate that a given argument is optional might seem like the easiest option ever! You can also use @Nullable annotation, it makes it clear and simple that a method can accept null arguments!
Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is passed. You can change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages, Java has no mechanism to change the value of an actual parameter.
You can use @IntDef or @StringDef annotations for your methods like this:
@Retention(SOURCE)
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
public @interface NavigationMode {}
public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;
...
public abstract void setNavigationMode(@NavigationMode int mode);
@NavigationMode
public abstract int getNavigationMode();
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With