Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从注释中查找方法_Java_Reflection - Fatal编程技术网

Java 从注释中查找方法

Java 从注释中查找方法,java,reflection,Java,Reflection,在Java中,可以从注释中找到方法吗? 例如: @Named("Qty") public getQty() { return _quantity; } @Named("Qty") public void setQty(long qty) { _quantity = qty; } 我知道这两个方法都被注释为“Qty”,如何在运行时检索setter方法?使用参数Qty查找所有用@Named注释的方法,然后查找名为getQty的方法,或者从注释的方法列表中,检查getter前缀。

在Java中,可以从注释中找到方法吗? 例如:

@Named("Qty") 
public getQty()
{
    return _quantity;
}

@Named("Qty")
public void setQty(long qty)
{
    _quantity = qty;
}

我知道这两个方法都被注释为“Qty”,如何在运行时检索setter方法?

使用参数
Qty
查找所有用
@Named
注释的方法,然后查找名为
getQty
的方法,或者从注释的方法列表中,检查getter前缀。

代价高昂,首先在类getDeclaredMethods上使用,对于该方法,获取其命名注释,然后检查方法名称是否为“get[A-Z]”或“is[A-Z]”。最好用其他方式解决这个问题

您可以使用反射

使用和来迭代这些方法。使用该方法确定方法是否具有注释

Named attr = method . getAnnotation ( Named . class ) ;
if ( ( attr != null ) && ( attr . value == "Qty" ) ) ...
使用库,您可以执行以下操作:

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; }
        });
Reflections=newreflections(“my.package”,newmethodAnnotationsCanner());
Set namedMethods=reflections.getMethodsAnnotatedWith(Names.class);
//甚至
设置qtyMethods=reflections.getMethodsAnnotatedWith(
新命名(){
公共字符串值(){返回“数量”;}

像Joop提到的公共类,它的成本非常高。你有其他的实现吗?它可能不一定是基于反射的。如果你需要基于注释参数定位一个方法,我不知道你的选项是什么。你可以改为注释属性,避免对本质上相同的东西使用两个注释。我我愿意接受建议。这个想法基于关键字“数量”我想很容易地检索getter和setter。我听说过一种叫做java bean属性的东西,你认为它能帮上忙吗?你可以看看JPA,比如eclipseLink。从数据库到java类的O/R映射是唯一一种类似的应用程序。这在某种程度上属于java bean属性类别。
import static org.reflections.ReflectionsUtils.*;
Set<Method> setterMethods = getAll(methods, withPrefix("set"));