美文网首页
Java自定义注解

Java自定义注解

作者: MC_Honva | 来源:发表于2018-01-11 15:50 被阅读12次

    Java提供了四种元注解来注解其他注解

    • @Target
    • @Retention
    • @Inheried
    • @Documented

    较为重要的是前面2个,target和retention,下面分别一个一个解释其用途。

    @Target:

    作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)

    取值(ElementType)有:

    1. ElementType.CONSTRUCTOR:用于描述构造器
    2. ElementType.FIELD:用于描述域
    3. ElementType.LOCAL_VARIABLE:用于描述局部变量
    4. ElementType.METHOD:用于描述方法
    5. ElementType.PACKAGE:用于描述包
    6. ElementType.PARAMETER:用于描述参数
    7. ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明
    @Retention:

    作用:用于描述注解的生命周期(即:被描述的注解在什么范围内有效)

    取值(RetentionPoicy)有:

    1. RetentionPolicy.SOURCE:在源文件中有效(即源文件保留),编译时被丢掉
    2. RetentionPolicy.CLASS:在class文件中有效(即class保留),但会被VM丢弃(默认)
    3. RetentionPolicy.RUNTIME:内存中的字节码,VM将在运行时也保留注解,因此可以通过反射机制读取注解的信息
    @Inherited

    指定子类可以继承父类的注解,只能是类上的注解,方法和字段的注解不能继承。即如果父类上的注解是@Inherited修饰的就能被子类继承。

    @Documented

    作用:指定被标注的注解会包含在javadoc中,即对应的方法生成javadoc的API文档时,会显示有这样的注解

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

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface testNoDoc {
        
    }
    
    

    public class Demodoc {
        @testDoc
        public void test(){
            
        }
        @testNoDoc
        public void testNoDoc(){
            
        }
    }
    

    上述代码生成javadoc后,如下图
    [图片上传失败...(image-d73013-1515656945658)]

    SpringMVC自定义注解需要在配置文件中添加注解代理

    <!-- <mvc:annotation-driven/> -->
        <aop:aspectj-autoproxy proxy-target-class="true" />
    

    下图为Java注解的基础知识点导图


    25200814-475cf2f3a8d24e0bb3b4c442a4b44734.jpg

    参考地址:http://www.cnblogs.com/peida/archive/2013/04/26/3038503.html

    相关文章

      网友评论

          本文标题:Java自定义注解

          本文链接:https://www.haomeiwen.com/subject/dsqtoxtx.html