java运行时获取自定义的Annotation

获取自定义的Annotation,靠的是反射机制的支持;

package com.mldn;

import .lang.annotation.Annotation;

import .lang.annotation.Retention;

import .lang.annotation.RetentionPolicy;

import .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();

}

if (me.isAnnotationPresent(MyAnnotation.class)) // 当前元素上是否存在该类型的Annotation

{

MyAnnotation man = me.getAnnotation(MyAnnotation.class); // 获取该方法上使用的在运行时活动的该类型的Annotation;

String str = man.value(); // 取出当前Annotation的value值,注意:()!

System.out.println(“自定义Annotation:” + MyAnnotation.class.getName() + ” value = ” + str);

}

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

System.out.println(“所有当前方法上使用的RUNTIME范围的Annotation:”);

for (Annotation a : an)

{

System.out.println(a);

}

}

}

class AnnUse

{

@MyAnnotation(value = “www.k187.com”) // 使用自定义Annotation

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

@Deprecated // 不建议使用

@Override // 覆写的方法

public String toString()

{

// 覆写

return “This is a Override funcation!”;

}

}

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 智乐兔
转载请注明:转自《java运行时获取自定义的Annotation
本文地址:https://www.zhiletu.com/archives-149.html
关注公众号:智乐兔

赞赏

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

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!

在线客服
在线客服 X

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

智乐兔官微