栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java寻找具有特定注释的方法及其注释元素

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java寻找具有特定注释的方法及其注释元素

这是一个方法,该方法返回带有特定注释的方法:

public static List<Method> getMethodsAnnotatedWith(final Class<?> type, final Class<? extends Annotation> annotation) {    final List<Method> methods = new ArrayList<Method>();    Class<?> klass = type;    while (klass != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance        // iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation        for (final Method method : klass.getDeclaredMethods()) { if (method.isAnnotationPresent(annotation)) {     Annotation annotInstance = method.getAnnotation(annotation);     // TODO process annotInstance     methods.add(method); }        }        // move to the upper class in the hierarchy in search for more methods        klass = klass.getSuperclass();    }    return methods;}

可以轻松修改它以满足您的特定需求。请注意,提供的方法会遍历类层次结构,以查找带有所需批注的方法。

这是满足您特定需求的方法:

public static List<Method> getMethodsAnnotatedWithMethodXY(final Class<?> type) {    final List<Method> methods = new ArrayList<Method>();    Class<?> klass = type;    while (klass != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance        // iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation        for (final Method method : klass.getDeclaredMethods()) { if (method.isAnnotationPresent(MethodXY.class)) {     MethodXY annotInstance = method.getAnnotation(MethodXY.class);     if (annotInstance.x() == 3 && annotInstance.y() == 2) {       methods.add(method);     } }        }        // move to the upper class in the hierarchy in search for more methods        klass = klass.getSuperclass();    }    return methods;}

要调用找到的方法,请参考教程。这里的潜在困难之一是方法参数的数量,这些参数在找到的方法之间可能会有所不同,因此需要进行一些额外的处理。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/595224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号