六、枚举类与注解(Enum、Annotation)

tech2025-04-13  2

一、枚举类      在没有枚举类型时定义常量常见的方式如下:

public class DayDemo { public static final int MONDAY =1; public static final int TUESDAY=2; public static final int WEDNESDAY=3; public static final int THURSDAY=4; public static final int FRIDAY=5; public static final int SATURDAY=6; public static final int SUNDAY=7; }

使用enum枚举类:

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } //测试 public class EnumDemo { public static void main(String[] args){ //直接引用 Day day =Day.MONDAY; } }

二、注解        从JDK5.0开始,Java增加了注解Annotation,例如@Override,@author等,可以在编译,类加载,运行时被读取,并执行相应的处理。通过使用Annotation,程序员可以在不改变原有逻辑的情况下,在源文件中嵌入一些补充信息。注解可用于修饰包,类,构造器,方法,成员变量,参数,局部变量的声明。        用处:        1.生成文档相关的注解        2.JDK内置的三个基本注解:              @Override,@Deprecated,@SuppressWarnings        3.跟踪代码依赖性,实现替代配置文件功能

A.自定义注解:

public @interface MyAnnotation { String value() default "hello"; }

元注解 :对现有的注解进行解释说明的注解。 jdk 提供的4种元注解:

1.Retention:指定所修饰的 Annotation 的生命周期:SOURCE\CLASS(默认行为\RUNTIME只声明为RUNTIME生命周期的注解,才能通过反射获取。 2.Target:用于指定被修饰的 Annotation 能用于修饰哪些程序元素 出现的频率较低 3.Documented:表示所修饰的注解在被javadoc解析时,保留下来。 4.Inherited:被它修饰的 Annotation 将具继承性。

@Inherited @Repeatable(MyAnnotations.class) @Retention(RetentionPolicy.RUNTIME) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})

B.可重复注解:

@Inherited @Repeatable(MyAnnotations.class) @Retention(RetentionPolicy.RUNTIME) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE}) public @interface MyAnnotation { String value() default "hello"; } @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE}) public @interface MyAnnotations { MyAnnotation[] value(); }

① 在MyAnnotation上声明@Repeatable,成员值为MyAnnotations.class ② MyAnnotation的Target和Retention等元注解与MyAnnotations相同。

最新回复(0)