java注解--Annotation
一、元注解:注解的注解
@Retention
@Target
@Document
@Inherited
1、@Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得 @Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
2、@Target:说明注解所修饰的对象范围
取值( ElementType )有:1.CONSTRUCTOR: 用于描述构造器
2.FIELD: 用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD: 用于描述方法
5.PACKAGE: 用于描述包
6.PARAMETER: 用于描述参数
7.TYPE: 用于描述类、接口(包括注解类型) 或enum声明
3、@Documented:
用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
4、@Inherited:
元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。二、定义
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AtFly {
public boolean orm() default true; //定义属性,赋予默认值
}
用法:
在User的一个字段中增加注解,如:
@AtFly(orm=false)
private String uName; //用户昵称
解析:
User u=new User();
for (Field f :u.getClass().getDeclaredFields()) {
if(f.isAnnotationPresent(AtFly.class)==true){
System.out.println(f.getName()+"元素,存在注解"+AtFly.class);
AtFly a=(AtFly)f.getAnnotation(AtFly.class);
System.out.println(a.orm()); //获得此注解的值
}else{
System.out.println(f.getName()+"元素,\t不存在");
}
}