Java自定义注解

自定义注解:

  使用@interface修饰符来定义注解类,在定义注解时,不能继承其他的注解或接口。注解类中的每一个方法实际上是声明了一个配置参数,且无入参无抛出异常。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。

  定义注解格式:
  public @interface 注解名 {定义体}

  注解参数的可支持数据类型:

    1.所有基本数据类型(int,float,boolean,byte,double,char,long,short)
    2.String类型
    3.Class类型
    4.enum类型
    5.Annotation类型
    6.以上所有类型的数组

  Annotation类型里面的参数该怎么设定: 
  第一,只能用public或默认(default)这两个访问权修饰.例如,String value();这里把方法设为defaul默认类型;   
  第二,参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和 String,Enum,Class,annotations等数据类型,以及这一些类型的数组.例如,String value();这里的参数成员就为String;  
  第三,如果只有一个参数成员,最好把参数名称设为"value",后加小括号。

Java提供了四个元注解,负责对Annotation进行说明。

@Target:

   @Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。

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

  取值(ElementType)有:

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

 

@Retention:

  @Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。

  作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)

  取值(RetentionPoicy)有:

    1.SOURCE:在源文件中有效(即源文件保留)
    2.CLASS:在class文件中有效(即class保留)
    3.RUNTIME:在运行时有效(即运行时保留)

  Retention meta-annotation类型有唯一的value作为成员,它的取值来自java.lang.annotation.RetentionPolicy的枚举类型值。

 

@Inherited:

  @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

  当@Inherited annotation类型标注的annotation的Retention是RetentionPolicy.RUNTIME,则反射API增强了这种继承性。如果我们使用java.lang.reflect去查询一个@Inherited annotation类型的annotation时,反射代码检查将展开工作:检查class和其父类,直到发现指定的annotation类型被发现,或者到达类继承结构的顶层。

 

@Documented:

  @Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。

 

如何读取注解--类上的注解

 
//取得类上的指定的注解  
Annotation annotation = 类.class.getAnnotation(MyAnnotation.class);  
  
//取得类上的所有注解,包括继承的注解。  
Annotation[] annotations = 类.class.getAnnotations();  
  
//取当前类上的所有的注解,不包括继承的  
Annotation[] annotations = 类.class.getDeclaredAnnotations();  

 

 

 

如何读取注解--方法上的注解

Method m=类.class.getMethod(String name, Class<?>... parameterTypes) ;
//或者得到所有方法
//Methods[] methods=类.class.getMethods() ;

//取得方法上的指定的注解  
Annotation annotation = m.getAnnotation(MyAnnotation.class);  
  
//取得方法上的所有注解,包括继承的注解。  
Annotation[] annotations = m.getAnnotations();  
  
//取当前方法上的所有的注解,不包括继承的  
Annotation[] annotations = m.getDeclaredAnnotations();  

 

自定义注解类:

@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
    String value() default "";
}

父类:

@MyAnnotation(value="类名上的注解")
public abstract class ParentClass {

    @MyAnnotation(value = "父类的abstractMethod方法")  
    public abstract void abstractMethod();  
  
    @MyAnnotation(value = "父类的doExtends方法")  
    public void doExtends() {  
        System.out.println(" ParentClass doExtends ...");  
    }  
      
    @MyAnnotation(value = "父类的doHandle方法")  
    public void doHandle(){  
        System.out.println(" ParentClass doHandle ...");  
    }  
}

子类:

public class ChildClass extends ParentClass{    
    
    //子类实现父类的抽象方法  
    @Override    
    public void abstractMethod() {    
        System.out.println("子类实现父类的abstractMethod抽象方法");    
    }    
      
    //子类继承父类的doExtends方法  
      
    //子类覆盖父类的doHandle方法  
    @Override    
    public void doHandle(){  
        System.out.println("子类覆盖父类的doHandle方法");   
    }  

}

测试类:

public class TestTool {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException {
        Class<ChildClass> clazz = ChildClass.class;

        if (clazz.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation cla = clazz.getAnnotation(MyAnnotation.class);
            System.out.println("子类继承到父类类上Annotation,其信息如下:" + cla.value());
        } else {
            System.out.println("子类没有继承到父类类上Annotation");
        }

        // 实现抽象方法测试
        Method method = clazz.getMethod("abstractMethod", new Class[]{});
        if (method.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation ma = method.getAnnotation(MyAnnotation.class);
            System.out
                    .println("子类实现父类的abstractMethod抽象方法,继承到父类抽象方法中的Annotation,其信息如下:"
                            + ma.value());
        } else {
            System.out
                    .println("子类实现父类的abstractMethod抽象方法,没有继承到父类抽象方法中的Annotation");
        }

        // 覆盖测试
        Method methodOverride = clazz.getMethod("doExtends", new Class[] {});
        if (methodOverride.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation ma = methodOverride.getAnnotation(MyAnnotation.class);
            System.out
                    .println("子类继承父类的doExtends方法,继承到父类doExtends方法中的Annotation,其信息如下:"
                            + ma.value());
        } else {
            System.out
                    .println("子类继承父类的doExtends方法,没有继承到父类doExtends方法中的Annotation");
        }

        // 继承测试
        Method method3 = clazz.getMethod("doHandle", new Class[] {});
        if (method3.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation ma = method3.getAnnotation(MyAnnotation.class);
            System.out
                    .println("子类覆盖父类的doHandle方法,继承到父类doHandle方法中的Annotation,其信息如下:"
                            + ma.value());
        } else {
            System.out
                    .println("子类覆盖父类的doHandle方法,没有继承到父类doHandle方法中的Annotation");
        }
    }
}

输出结果如下:

子类继承到父类类上Annotation,其信息如下:类名上的注解
子类实现父类的abstractMethod抽象方法,没有继承到父类抽象方法中的Annotation
子类继承父类的doExtends方法,继承到父类doExtends方法中的Annotation,其信息如下:父类的doExtends方法
子类覆盖父类的doHandle方法,没有继承到父类doHandle方法中的Annotation

当将注解类的@Inherit注释后,测试结果如下:

子类没有继承到父类类上Annotation
子类实现父类的abstractMethod抽象方法,没有继承到父类抽象方法中的Annotation
子类继承父类的doExtends方法,继承到父类doExtends方法中的Annotation,其信息如下:父类的doExtends方法
子类覆盖父类的doHandle方法,没有继承到父类doHandle方法中的Annotation

结论:

我们知道在编写自定义注解时,可以通过指定@Inherited注解,指明自定义注解是否可以被继承。

通过测试结果来看,@Inherited 只是可控制对类名上注解是否可以被继承。不能控制方法上的注解是否可以被继承。

 

总结:

1、JDK文档中的说明是:只有在类上应用的Annotation才能被继承,而实际应用时的结果是:除了类上应用的Annotation能被继承外,没有被重写的方法的Annotation也能被继承

2、要注意的是:当方法被重写后,Annotation将不会被继承。

3、要使得Annotation 被继承,需要在Annotation中加标识@Inherited,并且如果要被反射应用的话,就需要还有个@Retention(RetentionPolicy.RUNTIME) 标识。

4、Annotation的继承不能应用在接口上。

 

特别说明下spring事务注解@Transactional:

@java.lang.annotation.Target(value={java.lang.annotation.ElementType.METHOD,java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Inherited
@java.lang.annotation.Documented

@Transactional 注解应该只被应用到 public 可见度的方法上。

posted @ 2016-07-15 21:13  SaraMorning  阅读(316)  评论(0编辑  收藏  举报