美文网首页
Java中的注解

Java中的注解

作者: 暗香有独 | 来源:发表于2019-12-03 22:41 被阅读0次

    注解(annotation)

    最近项目中看到很多注解,一脸懵逼,注解什么东西,于是网上各种搜索折腾,网上找到的答案千篇一律,能讲明白的真的很少,看的也是迷迷糊糊,大概知道注解是和反射要搭配起来使用,如果只是单纯去看注解感觉很迷惑,自定义注解,然后可以放在类,接口,方法,属性,枚举中,可以填充注解中所需的参数,到底有什么用?注解到底干了什么?老子还是云里雾里的,不知所云。

    注解字面去理解就是对指定对象(类,方法,接口...)等等的一个说明。
    注解的创建末班:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    public @interface Other {
        String value() default "";
         int age();
         String[] names();
         annotaiton();
        ......
    }
    

    @Target:用于指定注解的作用域,那些对象可以使用该注解,例如ElementType.TYPE,指明注解可以应用到类,接口,枚举。
    ElementType.METHOD ,指明注解可以应用到方法中。
    ElementType.FIELD,指明注解可以应用到属性中。

    /** 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: 用于指定注解的声明周期。
    RetentionPolicy.SOURCE 指明注解编译前生效。
    RetentionPolicy.CLASS 指明注解可以编译在class类中。
    RetentionPolicy.RUNTIME 指明注解可以程序运行时生效。

    /**
         * 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,
    
        /**
         * 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:指明该对象可以生存和API文档。
    @Inherited: 该注解表明子类是有继承了父类的注解。比如一个注解被该元注解修饰,并且该注解的作用在父类上,那么子类有持有该注解。如果注解没有被该元注解修饰,则子类不持有父类的注解。

    看到这里是不是还是一脸的懵逼,这是弄啥嘞。

    这是我在网上找的一个例子,通过模拟Mybatis自动生成sql语句的例子,等看完这个例子获取你大概知道注解到底干了个啥。

    Go例子

    按照作者的给的例子,完成了整个代码,运行OK,回过头再看下例子,大概有点豁然开朗。

    总结下:单纯的注解是毫无意义的存在,必须配合反射技术的使用,才能凸显其价值,注解类似于一个无形的软桥,他会将被他注解的类中带的信息传递到一个指定的类中,通过反射技术获取到该类的信息,然后在做一些见不得人的的事情。

    相关文章

      网友评论

          本文标题:Java中的注解

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