检索 Java 注释属性 [英] Retrieve Java Annotation Attribute

查看:27
本文介绍了检索 Java 注释属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在带注释的方法上检索注释的值??

How can I retrieve the value of an annotation on the annotated method??

我有:

@myAnnotation(attribute1 = value1, attibute2 = value2)
public void myMethod()
{
  //I want to get value1 here
}

推荐答案

  1. 获取方法 实例.
  2. 获取注释.
  3. 获取注解属性值.

类似于:

Method m = getClass().getMethod("myMethod");
MyAnnotation a = m.getAnnotation(MyAnnotation.class);
MyValueType value1 = a.attribute1();

当然,您需要捕获/处理适当的异常.以上假设您确实是从当前类中检索方法(否则将 getClass() 替换为 Class.forName())并且所讨论的方法是公共的(使用 getDeclaredMethods() 如果不是这样)

You'll need to catch / handle the appropriate exceptions, of course. The above assumes you are indeed retrieving method from the current class (replace getClass() with Class.forName() otherwise) and the method in question is public (use getDeclaredMethods() if that's not the case)

这篇关于检索 Java 注释属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆