java_自定义注解_1

来源:互联网 发布:php 转为utf8 编辑:程序博客网 时间:2024/06/07 00:05

一.注解简介

1、元注解

元注解是指注解的注解。包括  @Retention @Target @Document @Inherited四种。

1.1、@Retention: 定义注解的保留策略

@Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
1.2、@Target:定义注解的作用目标

@Target(ElementType.TYPE)   //接口、类、枚举、注解

@Target(ElementType.FIELD) //字段、枚举的常量

@Target(ElementType.METHOD) //方法

@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR)  //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///   
1.3、@Document:说明该注解将被包含在javadoc中

1.4、@Inherited:说明子类可以继承父类中的该注解


掌握以上知识,可以自己写一个注解

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface Delete {    String description() default "user";    String key() default "delete";}

public class Dao {        @Delete(key="delete")    private String operation = "delete";        Integer delete(){        System.out.println(operation);        return 0;    }}

public class Test {    public static void main(String[] args) throws SecurityException,         NoSuchFieldException,         IllegalArgumentException,         IllegalAccessException {        Dao obj = new Dao();        Class<Dao> c = Dao.class;        Field field = c.getDeclaredField("operation");        field.setAccessible(true);        if(field.isAnnotationPresent(Delete.class)){            Delete delete = field.getAnnotation(Delete.class);            System.out.println(field.get(obj));            System.out.println(delete.key()+" "+delete.description());        }    }}

输出结果:

delete
delete user

这样我们就了解注解的基本工作原理了,下面将自定义注解使用在web项目中的框架验证。