读书人

枚举种enum

发布时间: 2012-09-06 10:37:01 作者: rapoo

枚举类enum

?

一般来说,我们希望每个美剧实例能够返回对自身的描述,

而不仅仅只是默认的toString()实现,这只能返回枚举实例的名字。

为此,你可以提供一个构造器,专门负责处理这个额外的信息,

然后添加一个方法,返回这个描述信息。

?

注意: 下面代码提供了个 private 的构造函数, 而且里面的参数是 ?额外信息的类型

?

?

public enum OzWitch {WEST("MIss GUICh"),NORTH("Glinda");private String description;private OzWitch(String desc){this.description = desc;}public String getDescription(){return description;}public static void main(String[] args) {for(OzWitch witch : OzWitch.values())System.out.println(witch+" : "+witch.getDescription());}}

?

例子2: 变形

public enum Meal2 {APPETIZE(Food.Appetizer.class),MAINCOURSE(Food.MainCourse.class);private Food[] values;private Meal2(Class<? extends Food> kind){values = kind.getEnumConstants();}public static void main(String[] args) {for(Meal2 meal : Meal2.values()){...}}} interface Food {enum Appetizer implements Food{SALAD, SOUP, SPRING_ROLLS;}enum MainCourse implements Food{LASAGNE, BURRITO, PAD_THAI;}}
?

?

?

注意,如果定义自己的方法,则必须在enum实例序列的最后添加

?

一个分号。同时, java要求必须先定义enum实例。 如果在enum

实例之前定义了任何方法或属性,那么在编译时就会得到错误信息。

?

?

?

2

覆盖toSting()方法,生成不同是字符串描述信息。

?

?

3

在swithc语句中使用enum


?

4利用反射来查看enum 中的 values()
enum Explore{HERE, THERE}public class Reflection {public static Set<String> analyze(Class<?> enumClass){System.out.println("---- Analyzing "+enumClass+"----");System.out.println("Interfaces");for(Type t : enumClass.getGenericInterfaces())System.out.println(t);System.out.println("Base: "+enumClass.getSuperclass());System.out.println("Methods: ");Set<String> methods = new TreeSet<String>();for(Method m : enumClass.getMethods())methods.add(m.getName());System.out.println(methods);return methods;}public static void main(String[] args) {Set<String> exploreMethods = analyze(Explore.class);Set<String> enumMethods = analyze(Enum.class);System.out.println("Explore.containsAll(Enum)?"+exploreMethods.containsAll(enumMethods));System.out.println("Explore.removeAll(enum):-"+exploreMethods.removeAll(enumMethods));System.out.println(exploreMethods);OSExcute.command("javap Explore");}}
?答案是, values()是由编译器添加的static方法,可以看出在创建Explore的过程中,编译器还为其添加了valueOf()方法,这可能有点令人迷惑,Enum类不是已经有valueOf()方法了嘛。不过Enum中的valueOf()方法需要2个参数,而这个新增的方法只需一个参数。由于这里使用的Set只是存储方法的名字,而不考虑方法的签名,所以在调用Explore.removeAll(Enum)之后,就只剩下[values]了。
如果将enum实例向上转型为Enum,那么values()方法就不可访问了。不过,在Class中有一个getEnuConstants()方法,所以即便Enum接口中没有values()方法,我们仍然可以通过Class对象获得所有enum实例
public class UpcastEnum{public static void main(String[] args){Search[] vals = Search.values();Enum e = Search.HIGHER;// e.values(); // No values() in Enumfor(Enum en : e.getClass().getEnumConstants())System.out.println(en);}}
?因为getEnumConstant()是Class上的方法,所以你甚至可以对不是每句的类调用此方法:只不过,此时该方法返回null,所以当你试图使用其返回的结果时回发生异常。

读书人网 >编程

热点推荐