java-自定义注解

来源:互联网 发布:什么是数据库的安全性 编辑:程序博客网 时间:2024/06/08 15:17

java-自定义注解

标签(空格分隔): java

  • java-自定义注解
  • 注解定义
    • 元注解介绍元注解定义注解的注解
      • Target
      • Retention
      • Documented
      • Inherited
    • 自定义注解
    • 总结


在现在的java中,注解的使用几乎是无处不在,下面记录一下自定义注解及注解的使用。

注解定义

元注解介绍:(元注解:定义注解的注解)

@Target

修饰注解的范围,是一个枚举类型,主要有以下几个选项。

public enum ElementType {    /** Class, interface (including annotation type), or enum declaration */    TYPE,    /** Field declaration (includes enum constants) */    FIELD,    /** Method declaration */    METHOD,    /** Formal parameter declaration */    PARAMETER,    /** Constructor declaration */    CONSTRUCTOR,    /** Local variable declaration */    LOCAL_VARIABLE,    /** Annotation type declaration */    ANNOTATION_TYPE,    /** Package declaration */    PACKAGE,    /**     * Type parameter declaration     *     * @since 1.8     */    TYPE_PARAMETER,    /**     * Use of a type     *     * @since 1.8     */    TYPE_USE}

@Retention

注解的生命周期。同样是枚举类。这里的选择根据注解的应用来选择,一般情况下,在javaweb开发中,采用的是RUNTIME值。这样可以使用java的反射来获取其中的值。

public enum RetentionPolicy {    /**     * Annotations are to be discarded by the compiler.#源文件保留     */    SOURCE,    /**     * Annotations are to be recorded in the class file by the compiler     * but need not be retained by the VM at run time.  This is the default     * behavior.  #class保留     */    CLASS,    /**     * Annotations are to be recorded in the class file by the compiler and     * retained by the VM at run time, so they may be read reflectively.     * #运行时保留     * @see java.lang.reflect.AnnotatedElement     */    RUNTIME}

@Documented

主要用来标记是否可以被javadoc进行文档化,标记注解,没有成员。下面是Documented注解源码,可以看到,这是一个运行时的注解。作用范围是注解类型

@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Documented {}

@Inherited

也是一个标记注解。标记被标记类型是被继承的。也就是允许子类继承父类的注解。

自定义注解

我们定义一个Dao注解。

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interface Dao {    public String value() default "";}

然后写一个类,用Dao注解

@Dao("userDao")public class UserDao {    public void add(){        System.out.println("add method ...");    };}

然后写一个测试类,来获取注解。

@Test    public void testSet() throws Exception {        Class<?> clazz = UserDao.class;        if(clazz.isAnnotationPresent(Dao.class)){            Dao dao = clazz.getAnnotation(Dao.class);            System.out.println(dao.value());        }    }

这样就能获取到注解里的值。

总结

其实可以把注解看为另一种xml,只不过比xml更方便。当然,注解里面可以写多个属性。比如

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Action {    public String ActionName() default "";    public String Result() default "";}
0 0
原创粉丝点击