(学习笔记)java反射编程-反射与Annotation

Annotation(Java注解),是从JDK1.5开始引入的一种注释机制。
在进行类、方法、变量、参数和包定义的时候都可以使用Annotation进行标注。

在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注。

通过反射可以获取标注的内容,在java.lang.reflect里面有一个AccessibleObject类,提供有获取Annotation类的方法。
// 获取全部Annotation
public Annotation[] getAnnotations();
//获取指定Annotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
定义一个接口,并且在接口上使用Annotation
package com.ys.annotation;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@FunctionalInterface
@Deprecated
interface IMessage {  // 有两个Annotation
    public void send(String msg);
}
@SuppressWarnings("serial") // 无法在程序执行的时候获取
class MessageImpl implements IMessage, Serializable {

    @Override // 无法在程序执行的时候获取
    public void send(String msg) {
        System.out.println("消息发送:" + msg);
    }
}
public class AnnotationDemo {
    public static void main(String[] args) throws Exception {
        {
            //获取接口上的Annotation信息
            Annotation[] annotations = IMessage.class.getAnnotations();
            for(Annotation temp : annotations) {
                System.out.println(temp);
            }
        }
        System.out.println("------------------------------------");
        {
            // 获取MessageImpl子类上的Annotation
            Annotation[] annotations = MessageImpl.class.getAnnotations();
            for(Annotation temp : annotations) {
                System.out.println(temp);
            }
        }
        System.out.println("------------------------------------");
        {
            // 获取MessageImpl.toString()方法上的Annotation
            Method methods = MessageImpl.class.getDeclaredMethod("send",String.class);
            Annotation[] annotations = methods.getAnnotations();
            for(Annotation temp : annotations) {
                System.out.println(temp);
            }
        }
    }
}

运行结果

@java.lang.FunctionalInterface()
@java.lang.Deprecated()
------------------------------------
------------------------------------

通过这份代码可以了解到,不同的Anontation有它的存在的范围,下面对比两个Anontation。

@FunctionalInterface
    //定义
    @Documenged
    @Retention(RetentionPolicy.RUNTIME) // 运行时生效
    @Targen(ElementType.TYPE)
    public @interface FunctionalInterface {}
@SupperssWarnings
    @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE})
    @Retention(RetentionPolicy.SOURCE) // 源代码时生效
    public @interface SuppressWarnings {}

通过RetentionPolicy可以看出程序执行的时候可以获取@FunctionalInterface,而@SupperssWarnings是在源代码编写的时候有效。
而在RetentionPolicy枚举类中海油一个class的定义,指的是在类定义的时候生效。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。