Loading... ## 简介 Annotation 是从JDK5.0开始引入的新技术。 作用:不是程序本身,可以对程序作出解释;可以被编译器读取。 格式:`@注释名`,还可以加一些参数值,如`@SuppressWarnings(Value = "unchecked")` 使用:可以在package,class,method,field等上面,相当于给他们添加了额外的辅助信息,可以通过反射机制编程实现对这些元数据的访问。 ---------- ## 内置注解 `@Override`: 重写 `@Deprecated`: 已过时的 `@SuppressWarnings`: 镇压警告,参数有"unchecked","all"等 ---------- ## 元注解 meta-annotation,他们用于对其他注解做说明,生成自定义的/内置注解。总共只有4个。 |元注解名|作用| ----| --- | @Target | 用于描述注解使用范围(ElementType.METHOD等) | | @Retention | 用于描述注解的生命周期(SOURCE < CLASS < RUNTIME)| | @Document | 说明将该注解包含在javadoc中 | | @Inherited | 说明子类可以继承父类的注解 | ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) // source < class < runtime @Documented @Inherited public @interface MyAnnotation{ } ``` ---------- ## 自定义注解 @interface用于声明一个注解 其中的每个方法实际是声明了一个配置参数 方法的名称就是参数的名称 返回值的类型就是参数的类型 可以通过default来声明参数的默认值 如果只有一个参数成员,一般参数值为value,此时在使用注解时,可以省略参数名 注解元素必须要有值,定义注解元素时,通常使用空字符串、0等作为默认值 ```java // 限定该自定义注解定义的范围:在类或者方法上 @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) // source < class < runtime @interface MyAnnotation{ // 注解的参数: 参数类型 + 参数名() String name() default ""; int age() default 0; int id() default -1; // 默认值为-1,代表不存在 String[] schools() default {"清华大学", "上海大学"}; } ``` 最后修改:2020 年 07 月 28 日 01 : 42 PM © 允许规范转载