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

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

问题描述

我怎样才能检索批注的方法??一个注解的值

我有:

  @myAnnotation(ATTRIBUTE1 =值,attibute2 =值2)
公共无效myMethod的()
{
  //我想在这里得到值1
}


解决方案

  1. 方法 实例。

  2. 获取注释。

  3. 获取标注属性值。​​

是这样的:

 方法M =的getClass()实现getMethod(myMethod的);
MyAnnotation A = m.getAnnotation(MyAnnotation.class);
MyValueType值1 = a.attribute1();

您需要赶上/处理适当的例外,当然。以上假定您确实是从当前类检索方法(更换的getClass()的Class.forName(),否则)和有关方法是公共的(使用 getDeclaredMethods()如果不是这种情况)

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

I have:

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

解决方案

  1. Obtain Method instance.
  2. Obtain annotation.
  3. Obtain annotation attribute value.

Something like:

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

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天全站免登陆