枚举基础用法详解

枚举基础用法详解 // 枚举基础用法声明、赋值、输出、比较和switch控制 enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland } class EnumDemo { public static void main(String args[]) { Apple ap Apple.RedDel; System.out.println(Value of ap: ap); // 输出枚举值 if (ap Apple.GoldenDel) // 枚举值比较 System.out.println(ap contains GoldenDel. ); switch (ap) { // 枚举控制switch语句 case Jonathan: System.out.println(Jonathan is red.); break; case GoldenDel: System.out.println(Golden Delicious is yellow.); break; // ... 其他case } } }// 使用枚举内置方法values()和valueOf() enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland } class EnumDemo2 { public static void main(String args[]) { // 获取所有枚举常量 Apple[] allapples Apple.values(); // values()返回枚举数组 for (Apple a : allapples) System.out.println(a); // 通过名称获取枚举实例 Apple ap Apple.valueOf(Winesap); // valueOf()根据字符串返回枚举 System.out.println(ap contains ap); } }// 枚举构造函数、实例变量和方法 enum Apple { Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8); private int price; // 实例变量 Apple(int p) { price p; } // 构造函数 int getPrice() { return price; } // 实例方法 } class EnumDemo3 { public static void main(String args[]) { // 访问枚举实例的方法 System.out.println(Winesap costs Apple.Winesap.getPrice() cents. ); // 遍历所有枚举值并调用方法 for (Apple a : Apple.values()) System.out.println(a costs a.getPrice() cents.); } }// 枚举重载构造函数 enum Apple { Jonathan(10), GoldenDel(9), RedDel, Winesap(15), Cortland(8); // RedDel使用默认构造函数 private int price; Apple(int p) { price p; } // 带参构造函数 Apple() { price -1; } // 无参构造函数重载 int getPrice() { return price; } }// 枚举方法ordinal()、compareTo()和equals() enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland } class EnumDemo4 { public static void main(String args[]) { // 获取枚举常量的序数声明位置 for (Apple a : Apple.values()) System.out.println(a a.ordinal()); // ordinal()返回序数 Apple ap Apple.RedDel; Apple ap2 Apple.GoldenDel; Apple ap3 Apple.RedDel; // 比较枚举顺序 if (ap.compareTo(ap2) 0) // compareTo()比较序数 System.out.println(ap comes before ap2); // 比较枚举相等性 if (ap.equals(ap3)) // equals()比较内容 System.out.println(ap equals ap3); if (ap ap3) // 比较引用 System.out.println(ap ap3); } }// 枚举应用示例决策器 import java.util.Random; enum Answers { NO, YES, MAYBE, LATER, SOON, NEVER } // 答案枚举 class Question { Random rand new Random(); Answers ask() { int prob (int) (100 * rand.nextDouble()); // 根据概率返回不同枚举值 if (prob 15) return Answers.MAYBE; else if (prob 30) return Answers.NO; // ... 其他概率分支 else return Answers.NEVER; } } class AskMe { static void answer(Answers result) { switch (result) { // 根据枚举值输出不同结果 case NO: System.out.println(No); break; case YES: System.out.println(Yes); break; // ... 其他case } } public static void main(String args[]) { Question q new Question(); answer(q.ask()); // 随机获取并输出答案 answer(q.ask()); } }// 包装类基本用法手动装箱和拆箱 class Wrap { public static void main(String args[]) { Integer iOb Integer.valueOf(100); // 手动装箱int - Integer int i iOb.intValue(); // 手动拆箱Integer - int System.out.println(i iOb); // 输出100 100 } }// 自动装箱和拆箱 class AutoBox { public static void main(String args[]) { Integer iOb 100; // 自动装箱编译器转换为Integer.valueOf(100) int i iOb; // 自动拆箱编译器转换为iOb.intValue() System.out.println(i iOb); // 输出100 100 } }// 自动装箱/拆箱在方法参数和返回值中的应用 class AutoBox2 { static int m(Integer v) { // 参数自动装箱返回值自动拆箱 return v; // 自动拆箱为int } public static void main(String args[]) { Integer iOb m(100); // 参数100自动装箱返回值自动装箱 System.out.println(iOb); } }// 表达式中的自动装箱/拆箱 class AutoBox3 { public static void main(String args[]) { Integer iOb 100; iOb; // 自动拆箱-自增-自动装箱 System.out.println(After iOb: iOb); Integer iOb2 iOb (iOb / 3); // 表达式计算中自动拆箱/装箱 int i iOb (iOb / 3); // 结果不装箱 System.out.println(i after expression: i); } }// 混合类型表达式中的自动装箱/拆箱 class AutoBox4 { public static void main(String args[]) { Integer iOb 100; Double dOb 98.6; dOb dOb iOb; // iOb自动拆箱为int提升为double与dOb相加 System.out.println(dOb after expression: dOb); } }// Boolean和Character的自动装箱/拆箱 class AutoBox5 { public static void main(String args[]) { Boolean b true; // 自动装箱 if (b) System.out.println(b is true); // 条件表达式中自动拆箱 Character ch x; // 自动装箱 char ch2 ch; // 自动拆箱 System.out.println(ch2 is ch2); } }// 手动拆箱错误示例 class UnboxingError { public static void main(String args[]) { Integer iOb 1000; // 自动装箱 int i iOb.byteValue(); // 错误手动调用byteValue()导致数据截断 System.out.println(i); // 输出241000超出byte范围 } }// 注解基础定义和使用import java.lang.annotation.*; import java.lang.reflect.*; Retention(RetentionPolicy.RUNTIME) // 注解保留到运行时 interface MyAnno { String str(); int val(); } class Meta { MyAnno(str Annotation Example, val 100) // 应用注解 public static void myMeth() { try { Class? c Meta.class; Method m c.getMethod(myMeth); MyAnno anno m.getAnnotation(MyAnno.class); // 获取注解 System.out.println(anno.str() anno.val()); } catch (NoSuchMethodException exc) { System.out.println(Method Not Found.); } } public static void main(String args[]) { myMeth(); } }// 带参数方法的注解 import java.lang.annotation.*; import java.lang.reflect.*; Retention(RetentionPolicy.RUNTIME) interface MyAnno { String str(); int val(); } class Meta { MyAnno(str Two Parameters, val 19) public static void myMeth(String str, int i) { try { Class? c Meta.class; // 获取带参数的方法 Method m c.getMethod(myMeth, String.class, int.class); MyAnno anno m.getAnnotation(MyAnno.class); System.out.println(anno.str() anno.val()); } catch (NoSuchMethodException exc) { System.out.println(Method Not Found.); } } public static void main(String args[]) { myMeth(test, 10); } }// 多个注解和类级别注解 import java.lang.annotation.*; import java.lang.reflect.*; Retention(RetentionPolicy.RUNTIME) interface MyAnno { String str(); int val(); } Retention(RetentionPolicy.RUNTIME) interface What { String description(); } What(description An annotation test class) // 类注解 MyAnno(str Meta2, val 99) class Meta2 { What(description An annotation test method) // 方法注解 MyAnno(str Testing, val 100) public static void myMeth() { Meta2 ob new Meta2(); try { // 获取类的所有注解 Annotation annos[] ob.getClass().getAnnotations(); System.out.println(All annotations for Meta2:); for (Annotation a : annos) System.out.println(a); // 获取方法的所有注解 Method m ob.getClass().getMethod(myMeth); annos m.getAnnotations(); System.out.println(All annotations for myMeth:); for (Annotation a : annos) System.out.println(a); } catch (NoSuchMethodException exc) { System.out.println(Method Not Found.); } } public static void main(String args[]) { myMeth(); } }// 注解默认值 import java.lang.annotation.*; import java.lang.reflect.*; Retention(RetentionPolicy.RUNTIME) interface MyAnno { String str() default Testing; // 默认值 int val() default 9000; } class Meta3 { MyAnno() // 使用默认值 public static void myMeth() { Meta3 ob new Meta3(); try { Class? c ob.getClass(); Method m c.getMethod(myMeth); MyAnno anno m.getAnnotation(MyAnno.class); System.out.println(anno.str() anno.val()); // 输出默认值 } catch (NoSuchMethodException exc) { System.out.println(Method Not Found.); } } public static void main(String args[]) { myMeth(); } }// 标记注解无成员 import java.lang.annotation.*; import java.lang.reflect.*; Retention(RetentionPolicy.RUNTIME) interface MyMarker { } // 标记注解 class Marker { MyMarker // 应用标记注解 public static void myMeth() { Marker ob new Marker(); try { Method m ob.getClass().getMethod(myMeth); // 检查注解是否存在 if (m.isAnnotationPresent(MyMarker.class)) System.out.println(MyMarker is present.); } catch (NoSuchMethodException exc) { System.out.println(Method Not Found.); } } public static void main(String args[]) { myMeth(); } }// 单成员注解 import java.lang.annotation.*; import java.lang.reflect.*; Retention(RetentionPolicy.RUNTIME) interface MySingle { int value(); // 单成员必须命名为value } class Single { MySingle(100) // 单成员注解可省略value public static void myMeth() { Single ob new Single(); try { Method m ob.getClass().getMethod(myMeth); MySingle anno m.getAnnotation(MySingle.class); System.out.println(anno.value()); // 访问value成员 } catch (NoSuchMethodException exc) { System.out.println(Method Not Found.); } } public static void main(String args[]) { myMeth(); } }// 类型注解Java 8 import java.lang.annotation.*; import java.lang.reflect.*; Target(ElementType.TYPE_USE) // 可用于任何类型使用处 interface TypeAnno { } Target(ElementType.TYPE_PARAMETER) // 用于类型参数 interface What { String description(); } Target(ElementType.FIELD) // 用于字段 interface EmptyOK { } Target(ElementType.METHOD) // 用于方法 interface Recommended { } class TypeAnnoDemoWhat(description Generic data type) T { // 类型参数注解 TypeAnno String str; // 类型注解 EmptyOK String test; // 字段注解 public TypeAnno Integer f2(int j, int k) { // 返回类型注解 return j k; } public Recommended Integer f3(String str) { // 方法注解 return str.length() / 2; } public void f4() throws TypeAnno NullPointerException { // 异常类型注解 // ... } String MaxLen(10) [] NotZeroLen [] w; // 数组注解 public static void myMeth(int i) { // 类型参数注解 TypeAnnoDemoTypeAnno Integer ob new TypeAnnoDemoTypeAnno Integer(); // 创建表达式注解 Unique TypeAnnoDemoInteger ob2 new Unique TypeAnnoDemoInteger(); Object x Integer.valueOf(10); Integer y; y (TypeAnno Integer) x; // 转换注解 } class SomeClass extends TypeAnno TypeAnnoDemoBoolean { } // 继承注解 }// 重复注解Java 8 import java.lang.annotation.*; import java.lang.reflect.*; Retention(RetentionPolicy.RUNTIME) Repeatable(MyRepeatedAnnos.class) // 指定容器注解 interface MyAnno { String str() default Testing; int val() default 9000; } Retention(RetentionPolicy.RUNTIME) interface MyRepeatedAnnos { // 容器注解 MyAnno[] value(); } class RepeatAnno { MyAnno(str First annotation, val -1) // 重复注解 MyAnno(str Second annotation, val 100) public static void myMeth(String str, int i) { RepeatAnno ob new RepeatAnno(); try { Class? c ob.getClass(); Method m c.getMethod(myMeth, String.class, int.class); // 通过容器注解获取重复注解 Annotation anno m.getAnnotation(MyRepeatedAnnos.class); System.out.println(anno); } catch (NoSuchMethodException exc) { System.out.println(Method Not Found.); } } public static void main(String args[]) { myMeth(test, 10); } }参考来源Java bytecode instruction listingsfvr一micro使用说明_LaTeX listings 宏包使用说明一Java Search Tools Product ListingsJava bytecode instruction listingsandroid source code list