EchoDemo's Blogs

Java中反射与Annotation

1、MetaAnnotation概念

(1)MetaAnnotation也称为元Annotation,也是一种Annotation,可以对其他的Annotation进行注释。

(2)Java5.0提供了一些标准的MetaAnnotation:

1)@Retention

2)@Target

3)@Documented

4)@Inherited

(3)@Retention:控制被Retention注释的Annotation信息的保留时间长短。

@Retention(SOURCE/CLASS/RUNTIME)
public/default @interface Annotation名称{...}

a、SOURCE:Annotation信息在编译阶段被丢弃,仅保留在java源文件中。

b、CLASS(默认):Annotation信息在编译阶段被保留,保留到class文件中,但是运行阶段不存在。

c、RUNTIME:Annotation信息一直保存到运行阶段,直到退出虚拟机才被丢弃。

以上三个值是java.lang.annotation.RetentionPolicy这个类所提供的枚举值。

(4)@Target:表示一个Annotation的使用范围。

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.FIELD,...})
public/defalut @interface Annotation名字{...}

a、TYPE:只能在类或接口或枚举上使用。

b、METHOD:在方法中使用。

c、FIELD:在成员变量使用。

d、PARAMETER:在参数上使用。

e、CONSTRUCTOR:在构造中使用。

f、LOCAL_VARIABLE:在局部变量上使用。

g、ANNOTATION_TYPE:只能在Annotation中使用。

h、PACKAGE:只能在包中使用。

(5)@Documented:想要在使用者制作JavaDoc文件的同时,也一并将Annotation的讯息加入至API文件中。

@Documented
public/default @interface Annotation名称{...}

(4)@Inherited:表示一个Annotation是否允许被其子类继承下来。

@Inherited
public/default @inherited Annotation名称{...}

2、反射与Annotation

(1)一个Annotation真正起作用,必须结合反射机制,在java.lang.reflect反射包中提供AccessibleObject类来对Annotation进行操作,最常用的方法如下:

public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);//判断是否使用时指定的Annotation。

public Annotation[] getAnnotation();//得到全部的Annotation。

注:无反射,不注解。

3、举例说明

package com.iotek.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

public class ReflectAnnotationDemo {

    public static void main(String[] args) throws Exception {
        Class<?> classType = Class.forName("com.iotek.annotation.AnnotationTest");
        boolean flag = classType.isAnnotationPresent(Description.class);
        if(flag){
            Description description = classType.getAnnotation(Description.class);
            System.out.println("AnnotationTest's description-->" + description.value());

            Method[] methods = classType.getDeclaredMethods();
            for(Method method:methods){
                if(method.isAnnotationPresent(Author.class)){
                    Author author = method.getAnnotation(Author.class);
                    System.out.println("AnnotationTest's author-->" + author.name() + " from "+author.group());
                }
            }
        }
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@interface Author{
    String name();
    String group();
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@interface Description{
    String value();
}

@Description("这是一个用于测试的类")
class AnnotationTest{
    @Author(name="EchoDemo",group="com.iotek")
    public void test(){
        System.out.println("test over!");
    }
}
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------