注释 Annotation
自定义注释
- 使用@interface类似于class创建,创建customed Annotation,可以运用到方法、类、参数和包上,当程序在编译或者运行的时候,可以检测到这些标示,从而进行一些特殊的处理
- 示例:
@Documented
@Inherited
@Target({ElemenType.Filed, ElementType.Method, ElementType.Type})
@RunTime(RetentionPolicy.RUNTIME)
public @Interface Init{
String name() default "zhangsan";
}
元注解
标示定义注解中可能使用到的系统提供的注解
- @Target
- 表明该注解可以应用的java元素类型
- 也可以同时使用多个注解使用范围,@Target({ElementType.TYPE, ElementType.METHOD})
取值 | 作用 |
---|---|
CONSTRUCTOR | 用于描述构造器 |
FILED | 用于描述使用域 |
LOCAL_VARIAVLE | 用于描述局部变量 |
METHOD | 用于描述方法 |
PACKAGE | 用于描述包 |
PARAMETER | 用于描述参数 |
TYPE | 用于描述类、接口(包括注解类型)或Enum声明 |
- @Retention
- 表明注解的生命周期
- 使用RententionPolicy.RUNTIME, 程序运行的任何节点均存在
- RententionPolicy.SOURCE 只是用于注解,在编译器编译前,会放弃编译该注解
- RententionPolicy.ClASS 表示在编译时会进行编译,但是当程序运行时,会删除的注解
- 表明注解的生命周期
- @Documented
- 表明该注解标记的元素可以被Javadoc 或类似的工具文档化。
- @Inherited
- 表明使用了@Inherited注解的注解,所标记的类的子类也会拥有这个注解
-
注解中可以创建 属性Field
-
示例
public @interface myAnnotaion{ int age() default 18; String name(); } // 之后可以通过age()直接调取设置的Annotation // 可以通过default设置 默认值, 如果没有设置默认值,使用字段是需要手动设置
-
Method[] methods = User.class.getMethods();
for(methods: Method method){
if(method.isAnnotationPresent(Init.class)){
method.invok(user,init.name())
}
}