java中注解的学习

java 注解,从名字上看是注释,解释。但功能却不仅仅是注释那么简单。注解(Annotation) 为我们在代码中添加信息提供了一种形式化的方法,是我们可以在稍后 某个时刻方便地使用这些数据(通过 解析注解 来使用这些数据),常见的作用有以下几种:
1.生成文档。这是最常见的,也是java 最早提供的注解。常用的有@see @param @return 等;
2.跟踪代码依赖性,实现替代配置文件功能。比较常见的是spring 2.5 开始的基于注解配置。作用就是减少配置。现在的框架基本都使用了这种配置来减少配置文件的数量;
3.在编译时进行格式检查。如@Override放在方法前,如果你这个方法并不是覆盖了超类方法,则编译时就能检查出;

包 java.lang.annotation 中包含所有定义自定义注解所需用到的原注解和接口。如接口 java.lang.annotation.Annotation 是所有注解继承的接口,并且是自动继承,不需要定义时指定,类似于所有类都自动继承Object。

该包同时定义了四个元注解,Documented,Inherited,Target(作用范围,方法,属性,构造方法等),Retention(生命范围,源代码,class,runtime)。下面将在实例中逐个讲解他们的作用,及使用方法。

Inherited : 在您定义注解后并使用于程序代码上时,预设上父类别中的注解并不会被继承至子类别中,您可以在定义注解时加上java.lang.annotation.Inherited 限定的Annotation,这让您定义的Annotation型别被继承下来。注意注解继承只针对class 级别注解有效(这段建议看完全文后在来回顾)。
四个元注解分别是:@Target,@Retention,@Documented,@Inherited ,再次强调下元注解是java API提供,是专门用来定义注解的注解,其作用分别如下:
      @Target 表示该注解用于什么地方,可能的值在枚举类 ElemenetType 中,包括:
          ElemenetType.CONSTRUCTOR----------------------------构造器声明
          ElemenetType.FIELD --------------------------------------域声明(包括 enum 实例)
          ElemenetType.LOCAL_VARIABLE------------------------- 局部变量声明
          ElemenetType.METHOD ----------------------------------方法声明
          ElemenetType.PACKAGE --------------------------------- 包声明
          ElemenetType.PARAMETER ------------------------------参数声明
          ElemenetType.TYPE--------------------------------------- 类,接口(包括注解类型)或enum声明
           
     @Retention 表示在什么级别保存该注解信息。可选的参数值在枚举类型 RetentionPolicy 中,包括:
          RetentionPolicy.SOURCE ---------------------------------注解将被编译器丢弃
          RetentionPolicy.CLASS -----------------------------------注解在class文件中可用,但会被VM丢弃
          RetentionPolicy.RUNTIME VM-------将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
           
      @Documented 将此注解包含在 javadoc 中 ,它代表着此注解会被javadoc工具提取成文档。在doc文档中的内容会因为此注解的信息内容不同而不同。相当与@see,@param 等。
       
      @Inherited 允许子类继承父类中的注解。

第一个:@Target,动手在前面我们编写的注解上加上元注解。
第二个元注解: @Retention 参数 RetentionPolicy。有了前面的经验这个注解理解起来就简单多了,并且幸运的是这个注解还没有特殊的属性值。 简单演示下如何使用:
第三和第四个元注解就不再举例了。比较简单,也没有值,相信看过上面的解释也就清楚了。下面我们还是继续来深入的探讨下注解的使用。上面的例子都非常简单,注解连属性都没有。ok,下面我们就来定义一个有属性的注解,并在例子程序中获取都注解中定义的值。

开始之前将下定义属性的规则:
        @interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。

代码:

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD, 
         ElementType.FIELD, ElementType.CONSTRUCTOR,ElementType.LOCAL_VARIABLE,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestA {
    String name();
    int id() default 0;
    Class gid();
}

下面改下我们的测试类:

package com.tmser.annotation;
 
import java.util.HashMap;
import java.util.Map;
 
 
package annotation;

import java.util.HashMap;
import java.util.Map;

@TestA(name = "type", gid = Long.class)
// 使用了类注解
public class UserAnnotation {

    @TestA(name="param",id=1,gid=Long.class)
    // 使用了类成员注解
    private Integer age;

    @TestA(name="construct",id=2,gid=Long.class)
    // 使用了构造方法注解
    public UserAnnotation() {

    }

    @TestA(name="public method",id=3,gid=Long.class)
    // 使用了类方法注解
    public void a() {
        @TestA(name="local var",id=4,gid=Map.class)
        // 使用了局部变量注解
        Map m = new HashMap(0);
    }
    
    public void b(@TestA(name="parameter",id=5,gid=Integer.class) Integer a) { // 使用了方法参数注解

    }
}

 
下面到了最重要的一步了,就是如何读取我们在类中定义的注解。只要读取出来了使用的话就简单了。
package annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ParseAnnotation {
    public static void parseTypeAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("annotation.UserAnnotation");

        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            TestA testA = (TestA) annotation;
            System.out.println("id= " + testA.id() + " ;name=" + testA.name()
                    + " ;gid= " + testA.gid());
        }
    }

    public static void parseMethodAnnotation() {
        Method[] methods = UserAnnotation.class.getDeclaredMethods();
        for (Method method : methods) {

            boolean hasAnnotation = method.isAnnotationPresent(TestA.class);
            if (hasAnnotation) {

                TestA annotation = method.getAnnotation(TestA.class);
                System.out.println("method = " + method.getName() + " ; id = "
                        + annotation.id() + " ; description = "
                        + annotation.name() + "; gid= " + annotation.gid());
            }
        }
    }

    public static void parseConstructAnnotation() {
        Constructor[] constructors = UserAnnotation.class.getConstructors();
        for (Constructor constructor : constructors) {

            boolean hasAnnotation = constructor
                    .isAnnotationPresent(TestA.class);
            if (hasAnnotation) {

                TestA annotation = (TestA) constructor
                        .getAnnotation(TestA.class);
                System.out.println("constructor = " + constructor.getName()
                        + " ; id = " + annotation.id() + " ; description = "
                        + annotation.name() + "; gid= " + annotation.gid());
            }
        }
    }
    
    public static void parseParameterAnnotation(){
        Method[] methods = UserAnnotation.class.getDeclaredMethods();
        for (Method method : methods){
            Class<?>[] parameterTypes = method.getParameterTypes();            
            for (Class<?> clas : parameterTypes){
                                
                    //TestA annotation = (TestA)clas.getAnnotation(TestA.class);
                    System.out.println(" method= "+method+" has a parameter= "+
                    clas);
                    //+"; id ="+annotation.id()+"; description= "+annotation.name()+
                    //"; gid= "+annotation.gid());
                
            }            
            Annotation[][] annotationarrays = method.getParameterAnnotations();
            for (Annotation[] annotationarray : annotationarrays){
                for (Annotation annotationone : annotationarray){
                    //boolean hasAnnotation = annotationone.annotationType().e(annotation.TestA.class);
                        TestA annotation = (TestA)annotationone;
                        System.out.println(" method= "+method+" has a parameter= "+
                                "; id ="+annotation.id()+"; description= "+annotation.name()+
                                "; gid= "+annotation.gid());
                    }
                }
            }
        }
    

    public static void main(String[] args) throws ClassNotFoundException {
        parseTypeAnnotation();
        parseMethodAnnotation();
        parseConstructAnnotation();
        parseParameterAnnotation();
    }

}




运行:

id= 0 ;name=type ;gid= class java.lang.Long
method = a ; id = 3 ; description = public method; gid= class java.lang.Long
constructor = annotation.UserAnnotation ; id = 2 ; description = construct; gid= class java.lang.Long
 method= public void annotation.UserAnnotation.b(java.lang.Integer) has a parameter= class java.lang.Integer
 method= public void annotation.UserAnnotation.b(java.lang.Integer) has a parameter= ; id =5; description= parameter; gid= class java.lang.Integer



   最后提醒下:
    1. 要用好注解,必须熟悉java 的反射机制,从上面的例子可以看出,注解的解析完全依赖于反射。
     2. 不要滥用注解。平常我们编程过程很少接触和使用注解,只有做设计,且不想让设计有过多的配置时
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值