从注释中查找方法 [英] Find method from annotation
本文介绍了从注释中查找方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中可以从注解中找到方法吗?例如:
It is possible in Java to find a method from its annotations? For instance:
@Named("Qty")
public getQty()
{
return _quantity;
}
@Named("Qty")
public void setQty(long qty)
{
_quantity = qty;
}
我知道两者都被注释为数量",例如如何在运行时检索 setter 方法?
I know that both are annotated as "Qty", how can retrieve the setter method for example on runtime?
推荐答案
使用 Reflections图书馆,你可以这样做:
using the Reflections library, you can do something like this:
Reflections reflections = new Reflections("my.package", new MethodAnnotationsScanner());
Set<Method> namedMethods = reflections.getMethodsAnnotatedWith(Names.class);
//or even
Set<Method> qtyMethods = reflections.getMethodsAnnotatedWith(
new Named() {
public String value() { return "Qty"; }
public Class<? extends Annotation> annotationType() { return Named.class; }
});
然后,使用传统的 Java 反射很容易获得 setter 方法,尽管反射也可以在这里帮助您:
Then, it's easy to get just the setter methods using conventional java reflection, although Reflections can also help you here:
import static org.reflections.ReflectionsUtils.*;
Set<Method> setterMethods = getAll(methods, withPrefix("set"));
这篇关于从注释中查找方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文