java 各种类型的注解的作用范围

Annotation(注解)是有自己的作用保持范围的,不同的注解生命周期不同。

1 .lang.Annotation.Retention; Annotation保存范围定义;// Annotation类型

@Documented

@Retention(value=RUNTIME)

@Target(value=ANNOTATION_TYPE)

public @interface Retention

{

public abstract RetentionPolicy value(); // 保存范围

}

2 .lang.Annotation.RetentionPolicy; // 枚举类型

public enum RetentionPolicy

extends Enum

// RetentionPolicy有三种范围定义了Annotaion的保存范围:
1.SOURCE:此Annotation的信息保存在*.源文件中,之后不会保存在class文件中;
2.CLASS:保存在源文件中,后保存在class文件中,但不进入JVM;
3.RUNTIME:存在上述两种范围,并且进入JVM;只有在运行时存在的属性,才可以被反射机制获取到!
—–定义Annotation类并指定Retention属性:

package com.mldn;

import .lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

@Retention(value = RetentionPolicy.RUNTIME) // 定义当前Annotation的保持的有效范围:RUNTIME

public @interface MyAnnotation // 自定义注释

{

public int key() default 1;

}

// 系统内建的三种Annotation的Retention属性定义:
1.Override: @Retention(value=SOURCE),只在中有作用!
2.Deprecated: @Retention(value=RUNTIME),在运行时内起作用;
3.SuppressWarnings:@Retention(value=SOURCE),只在起作用;
//反射机制只能取得Deprecated类型;

———通过反射机制获取Annotation:

// Class:

public Annotation[] getAnnotations();

public Annotation[] getDeclaredAnnotations();

public A getAnnotation(Class annotationClass);

public boolean isAnnotation();

public boolean isAnnotationPresent(Class extends Annotation> annotationClass);

———-实例:

package com.mldn;

import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

public class ReflectAnnotation

{

public static void main(String[] args)

{

Class> c = null; // 声明反射的源头

Method me = null; // 方法

try

{

c = Class.forName(“com.mldn.AnnUse”); // 实例化

me = c.getDeclaredMethod(“toString”); // 通过反射获取方法

}

catch (ClassNotFoundException e)

{

e.printStackTrace();

}

catch (NoSuchMethodException e)

{

e.printStackTrace();

}

Annotation[] an = me.getAnnotations(); // 获取该方法上使用的所有在运行时活动的Annotation;

for (Annotation a : an)

{

System.out.println(a);

}

}

}

class AnnUse

{

@SuppressWarnings(“unchecked”) // 压制警告信息

@Deprecated // 不建议使用

@Override // 覆写的方法

public String toString()

{

// 覆写

return “This is a Override funcation!”;

}

}

/*

ubuntu@xu-desktop:~$ java com.mldn.ReflectAnnotation

@java.lang.Deprecated()

// 因为只有Deprecated是RUNTIME活动范围,所以反射机制获得的只有该Annotation;

*/

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 智乐兔
转载请注明:转自《java 各种类型的注解的作用范围
本文地址:https://www.zhiletu.com/archives-148.html
关注公众号:智乐兔

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!

在线客服
在线客服 X

售前: 点击这里给我发消息
售后: 点击这里给我发消息

智乐兔官微