Tiger 中的一个重要新特性是枚举构造,它是一种新的类型,允许用常量来表示特定的数据片断,而且全部都以类型安全的形式来表示。Tiger 专家、developerWorks 的多产作者 Brett McLaughlin 将解释枚举的定义,介绍如何在应用程序中运用枚举,以及它为什么能够让您抛弃所有旧的 public static final 代码。
您已经知道,Java 代码的两个基本的构造块是类 和接口。现在 Tiger 又引入了枚举,一般简称它为 enum。这个新类型允许您表示特定的数据点,这些数据点只接受分配时预先定义的值集合。
当然,熟练的程序员可以用静态常量实现这项功能,如清单 1 所示: 清单 1. public static final 的常量
public class OldGrade {
public static final int A = 1;
public static final int B = 2;
public static final int C = 3;
public static final int D = 4;
public static final int F = 5;
public static final int INCOMPLETE = 6;
}
说明:我要感谢 O'Reilly 媒体公司,该公司允许在本文中使用我撰写的 Java 1.5 Tiger: A Developer's Notebook 一书中“枚举”这一章中的代码示例(请参阅参考资料)。
然后您就可以让类接受像 OldGrade.B 这样的常量,但是在这样做的时候,请记住这类常量是 Java 中 int 类型的常量,这意味着该方法可以接受任何 int 类型的值,即使它和 OldGrade 中定义的所有级别都不对应。因此,您需要检测上界和下界,在出现无效值的时候,可能还要包含一个 IllegalArgumentException。而且,如果后来又添加另外一个级别(例如 OldGrade.WITHDREW_PASSING),那么必须改变所有代码中的上界,才能接受这个新值。
在枚举间切换
能够在枚举的值之间移动很好,但是更重要的是根据枚举的值进行决策。您当然可以写一堆 if (grade.equals(Grade.A)) 类型的语句,但那是在浪费时间。Tiger 能够很方便地把枚举支持添加到过去的好东西 switch 语句上,所以它很容易使用,而且适合您已知的内容。清单 6 向将展示如何解决这个难题:
清单 6. 在枚举之间切换
public void testSwitchStatement(PrintStream out) throws IOException {
StringBuffer outputText = new StringBuffer(student1.getFullName());
switch (student1.getGrade()) {
case A:
outputText.append(" excelled with a grade of A");
break;
case B: // fall through to C
case C:
outputText.append(" passed with a grade of ")
.append(student1.getGrade().toString());
break;
case D: // fall through to F
case F:
outputText.append(" failed with a grade of ")
.append(student1.getGrade().toString());
break;
case INCOMPLETE:
outputText.append(" did not complete the class.");
break;
}
out.println(outputText.toString());
}
在这里,枚举值被传递到 switch 语句中(请记住,getGrade() 是作为 Grade 的实例返回的),而每个 case 子句将处理一个特定的值。该值在提供时没有枚举前缀,这意味着不用将代码写成 case Grade.A,只需将其写成 case A 即可。如果您不这么做,编译器不会接受有前缀的值。
public void testSwitchStatement(PrintStream out) throws IOException {
StringBuffer outputText = new StringBuffer(student1.getFullName());
switch (student1.getGrade()) {
case A:
outputText.append(" excelled with a grade of A");
break;
case B: // fall through to C
case C:
outputText.append(" passed with a grade of ")
.append(student1.getGrade().toString());
break;
case D: // fall through to F
case F:
outputText.append(" failed with a grade of ")
.append(student1.getGrade().toString());
break;
case INCOMPLETE:
outputText.append(" did not complete the class.");
break;
default:
outputText.append(" has a grade of ")
.append(student1.getGrade().toString());
break;
}
out.println(outputText.toString());
}
研究以上代码可以看出,任何没有被 case 语句处理的枚举值都会被 default 语句处理。这项技术您应当坚持采用。原因是:假设 Grade 枚举被您的小组中其他程序员修改(而且他忘记告诉您这件事)成清单 8 所示的版本:
清单 8. 给 Grade 枚举添加一个值
package com.oreilly.tiger.ch03;
public enum Grade {
A, B, C, D, F, INCOMPLETE,
WITHDREW_PASSING, WITHDREW_FAILING
};
为每个状态码分配一些人们能读懂的错误信息,从而允许人们在 Ant 提供某个代码时查找合适的错误信息,将这些信息显示在控制台上。这是映射(Map)的一个绝好用例,在这里,每个映射(Map)的键都是一个枚举值,而每个值都是键的错误信息。清单 10 演示了该映射的工作方式:
清单 10. 枚举的映射(Map)
public void testEnumMap(PrintStream out) throws IOException {
// Create a map with the key and a String message
EnumMap<AntStatus, String> antMessages =
new EnumMap<AntStatus, String>(AntStatus.class);
// Initialize the map
antMessages.put(AntStatus.INITIALIZING, "Initializing Ant...");
antMessages.put(AntStatus.COMPILING, "Compiling Java classes...");
antMessages.put(AntStatus.COPYING, "Copying files...");
antMessages.put(AntStatus.JARRING, "JARring up files...");
antMessages.put(AntStatus.ZIPPING, "ZIPping up files...");
antMessages.put(AntStatus.DONE, "Build complete.");
antMessages.put(AntStatus.ERROR, "Error occurred.");
// Iterate and print messages
for (AntStatus status : AntStatus.values() ) {
out.println("For status " + status + ", message is: " +
antMessages.get(status));
}
}
该代码使用了泛型(generics)(请参阅参考资料)和新的 EnumMap 构造来建立新映射。而且,枚举值是通过其 Class 对象提供的,同时提供的还有映射值的类型(在该例中,它只是一个简单的字符串)。该方法的输出如清单 11 所示:
枚举的 Class 对象?
您可能已经注意到,清单 10 中的示例代码实际上表明 Tiger 把枚举当作类,这可以从AntStatus 的 Class 对象那里得到证明,该对象不仅可用,而且正被实际使用。这是真的。归根到底, Tiger 还是把枚举看成是特殊的类类型。有关枚举的具体实现细节,请参阅 Java 5.0 Tiger: A Developer's Notebook 的第三章(请参阅参考资料)。
清单 11. 清单 10 的输出
[echo] Running AntStatusTester...
[java] For status INITIALIZING, message is: Initializing Ant...
[java] For status COMPILING, message is: Compiling Java classes...
[java] For status COPYING, message is: Copying files...
[java] For status JARRING, message is: JARring up files...
[java] For status ZIPPING, message is: ZIPping up files...
[java] For status DONE, message is: Build complete.
[java] For status ERROR, message is: Error occurred.