Reputation: 664
I want to create a parameter with multiple possibilities. To be more precise, in the method, I would like to have different levels of warning like 0,1,2 and 3. When you type it gives you have only these 4 possibilities.
Eg: setFoobar(1, "Yo");
Upvotes: 0
Views: 70
Reputation: 11474
Consider using an enum
for that:
public enum Severity {
DEBUG, INFO, WARN, ERROR
}
[edit] Imagine, you have some method for logging a message with different urgency. The enum
signifies that. In your method, you could then do something like:
switch (severity) {
case DEBUG:
// ignore
break;
case INFO:
System.out.println(message);
break;
case WARN:
case ERROR:
System.err.println(message);
break;
}
... or just do some comparisons:
if (severity == Severity.WARN || severity == Severity.ERROR) {
System.err.println(message);
}
Beside that, an enum
is much like a normal class
, which means that you can add state (as in instance variables) and methods. For example, you could move the logic given above directly into the enum
like so:
public enum Severity {
DEBUG("Some low-level logging output"),
INFO("Informational output"),
WARN("A warning"),
ERROR("A serious error");
private String description;
private Severity(String description) {
this.description = description;
}
public void output(String message) {
switch (this) {
case DEBUG:
// ignore
break;
case INFO:
System.out.println(message);
break;
case WARN:
case ERROR:
System.err.println(message);
break;
}
}
public String getDescription() {
return description;
}
}
Upvotes: 3