Java – Prohibit passing certain values for method parameters

Prohibit passing certain values for method parameters… here is a solution to the problem.

Prohibit passing certain values for method parameters

I have such a method:

void method(int number){some code}

I’ll call it like this :

method(-1)

Is there a way in Java that only allows passing positive integers to numeric arguments instead of checking the method body or checking for exceptions?

Solution

Declaring a checked exception doesn’t make the method argument automatically validated in some way, it just means that the caller is obligated to check if it was thrown, even if the code called the literal method(1).

If your application is complex enough, you can use Bean Validation and impose constraints on method parameters:

void method(@Min(1) int number) { }

This is only worth it if you are already using a sufficiently complex system to support it, such as Spring or CDI. Otherwise, just insist on checking the method body and throw an IllegalArgumentException if the requirement fails. Guava’s Preconditions utility is useful here.

(Also, your code will be easier to read if you follow the common Java code standard.) Type names begin with an uppercase letter, but member and parameter names begin with a lowercase letter. )

Related Problems and Solutions