zoukankan      html  css  js  c++  java
  • java annotation使用介绍

    还望支持个人博客站:http://www.enjoytoday.cn

    介绍

    Annotation的中文名字叫注解,开始与JDK 1.5,为了增强xml元数据和代码的耦合性的产物。注解本身并没有业务逻辑处理,仅仅是一个声明,具体的处理需要交由使用这些注解的工具类或方法,原则上来说,注解应该是对代码书写的一个辅助,即注解是否存在均不能影响代码的正常运行。现在java中使用注解的场景是越来越多,如orm框架,Ioc框架等,开发人员使用注解的方式可以简化对于元数据的维护和构建(xml配置数据),接下来主要介绍自定义注解的方法和如何使用自定义注解。

    自定义注解

    和注解相关的java文件的位置在java.lang.annotation包下自定义注解比较简单 格式和一般的java文件类似,声明如下:

    @Documented
    @Target(ElementType.TYPE)
    @Retentiion(RetentionPolicy.RUNTIME)
    @Inherited
    public @interface annotation{
           int value() default -1;
    }

    如上所示就是一般注解定义的格式,其中在声明注解之前需要定义注解的使用场景等信息,即添加元注解,java提供的元注解有四类,介绍如下:

    1)@Documented
         一个简单的问但包含注解,添加即代表注解包含在Javadoc中,我们可以通过javadoc -d doc *.java生成一个java的doc文档。

    2)@Target
         声明注解的使用场景,默认为可用于任何场景,参数类型为枚举,包括的属性有如下:

    - ElementType.TYPE:在class,interface(包括@interface),enum声明前 - ElementType.FIELD:全局变量前 - ElementType.METHOD:方法前 - ElementType.PARAMETER:方法参数前 - ElementType.CONSTRUCTOR:构造方法前 - ElementType.LOCAL_VARIABLE:方法内部参数前 - ElementType.ANNOTATION_TYPE:@interface前 - ElementType.PACKAGE:用于记录java文件的package信息 **3)@Retention**      定义该注解的生命周期,参数类型如下: - RetentionPolicy.SOURCE:编译器要丢弃的注释。 - RetentionPolicy.CLASS: 编译器将把注释记录在类文件中,但在运行时 VM 不需要保留注释。默认为该属性 - RetentionPolicy.RUNTIME:编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。 **4)@Inherited**      该注解表明子类继承该注解,反之不继承。

    ## 使用 使用分三段介绍:首先给出注解的定义,然后给出注解的使用方式,最后给出注解的逻辑处理方法。 ### 自定义一个注解 注解的自定义声明为@interface默认继承Annotation接口,格式如下:
    /**
     * @date 17-2-8.
     * @className ClassTypeModel
     * @serial 1.0.0
     * @see Target @Target:设置注释引用的类型
     * @see ElementType  注释引用类型枚举 ElementType.TYPE:class interface(包括annotation),enum引用
     * @see Retention @Retention:注释适用范围
     * @see RetentionPolicy  注释使用类型枚举
     */
    
    @Documented
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @AnnotationTypeModel
    public @interface TypeModel {
        String value() default "TypeModel";
        int id() default -7;
        boolean isActive() default false;
        int value () default -1;
    
    }

    如上,注解中的方法的返回可以通过 default 设置默认返回值。

    注解的引用

    注解的使用需要根据注解已经声明的使用场景中使用,否则会包类型不匹配错误,使用如下:

    @TypeModel(id = 7, isActive = true,value = "MyClass")
    
    public class MyClass {
    
        @ConstructorTypeModel(id = 1000,isActive = true,value = "MyClass")
        public MyClass(){
            System.out.print("this is MyClass ConstructorTypeModel
    ");
            annotatioinTestMethod(true);
        }
    
    
        @FieldTypeModel(id = 10,isActive = true,value = "type")
        private String type;
        @FieldTypeModel(id = 11,isActive = true,value = "name")
        private String name;
        @FieldTypeModel(id = 10,isActive = true,value = "favorite")
        private String favorite;
    
    
        @MethodTypeModel(id = 5,isActive = true,value = "annotatioinTestMethod")
        private void annotatioinTestMethod(@ParamTypeModel(id = 6,isActive = true,value = "testparam") boolean isTest){
            @LocalVarTypeModel(isActive = true)
            boolean flag=isTest;
            System.out.print("this is annotationTestMethod.
    ");
    
        }
        ......
     }

    注解的处理

    注解在使用后我们可以通过java反射的原理获取到注解的值,方便从而方便我们之后的业务逻辑处理,处理如下:

    /**
         * 通过反射获取注入的内容
         */
        private static void reflectAnnotations(){
            MyClass myClass=new MyClass();
    //        //only jdk over 1.8
    //        MyClass myClass1=new @UseTypeModel(isActive = true) MyClass();
            Class<?> tClass=myClass.getClass();
            Annotation[] annotations= tClass.getDeclaredAnnotations();
            annotationPrint(annotations,"classAnnotations");
            Constructor<?>[] constructors=  tClass.getDeclaredConstructors();
            System.err.println("Constructor of all.
    ");
            for (Constructor<?> constructor:constructors){
                Annotation[] constructorDeclaredAnnotations= constructor.getDeclaredAnnotations();
                annotationPrint(constructorDeclaredAnnotations,"constructorDeclaredAnnotations");
            }
    
            System.err.println("Methods of all.
    ");
            Method[] methods=tClass.getDeclaredMethods();
            for (Method method:methods){
                Annotation[]  methodAnnotation=method.getDeclaredAnnotations();
    
    
                annotationPrint(methodAnnotation,"methodAnnotation");
    
                Annotation[][] paramAnnotations= method.getParameterAnnotations();
                for (Annotation[] annotation: paramAnnotations){
                    annotationPrint(annotation,"paramAnnotations");
                }
    
            }
            System.err.println("Field of all.
    ");
            Field[] fields=tClass.getDeclaredFields();
    
            for (Field field:fields){
                Annotation[] filedAnnotations=  field.getDeclaredAnnotations();
                annotationPrint(filedAnnotations,"filedAnnotations");
            }
    
        }
    
    
    
    
        private static void annotationPrint(Annotation[] annotations,String type){
            for (Annotation annotation: annotations){
                System.out.println(type+" toString:"+annotation.toString()+"
    ");
                Class<?> clazz= annotation.annotationType();
                System.out.println("annotation class name:"+clazz.getName());
                Annotation[] declaredAnnotations= clazz.getDeclaredAnnotations();
                //注释的注释
                for (Annotation annotation1:declaredAnnotations){
                    System.out.println(annotation.getClass().getSimpleName()+" annotation toString:"+annotation1.toString()+"
    ");
                }
            }
        }

    如上就是一个简单的注解demo介绍.

    源码

    源码下载地址:annotationdemojava

  • 相关阅读:
    Linux初级知识_04 -- 目录结构与目录管理
    查找无限整数序列的第n位1,2,3,4,5,6,7,8,9,10,11,...
    谷歌面试题:在半径为1的圆中随机选取一点
    FtpClient 调用storeFile 抛出 java.net.SocketException异常
    CountDownLatch 使用
    软件版本号比较 java工具类
    pcm文件转wav C语言
    unimrcp更改安装目录
    xpath学习记录
    jackson 实体转json 为NULL或者为空不参加序列化
  • 原文地址:https://www.cnblogs.com/amiko/p/7906236.html
Copyright © 2011-2022 走看看