我想创建一个具有多种可能性的参数。更确切地说,在方法中,我希望有不同级别的警告,如0,1,2和3.当你输入它时,你只有这四种可能性。
例如:setFoobar(1,“Yo”);
答案 0 :(得分:3)
考虑使用enum
:
public enum Severity {
DEBUG, INFO, WARN, ERROR
}
[edit]想象一下,你有一些记录不同紧急程度的消息的方法。 enum
表示。在您的方法中,您可以执行以下操作:
switch (severity) {
case DEBUG:
// ignore
break;
case INFO:
System.out.println(message);
break;
case WARN:
case ERROR:
System.err.println(message);
break;
}
......或者只是做一些比较:
if (severity == Severity.WARN || severity == Severity.ERROR) {
System.err.println(message);
}
除此之外,enum
与普通class
非常相似,这意味着您可以添加状态(如实例变量)和方法。例如,您可以将上面给出的逻辑直接移到enum
中,如下所示:
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;
}
}
答案 1 :(得分:0)
Java enums
可以提供此类功能。