有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Get类方法,带有org注释。重新选举

我用过org。反思(http://code.google.com/p/reflections/)在我的项目中,用于加载带有特定注释的类。现在我有了类,我需要得到我自己制作的所有带有注释的方法。但当我创建Reflections对象时,它只要求包名,所以如果我使用GetMethodsNotatedWith方法,它将从给定的包类中获取所有方法,但我想从我的类中获取方法。我该怎么做


共 (3) 个答案

  1. # 1 楼答案

    如果你有一个Class对象,那就相当简单了。见this reference

    重要的代码部分是:

    Class c = Class.forName(args[0]);
    Method m[] = c.getDeclaredMethods();
    

    这样,您就可以使用Method对象数组

  2. # 2 楼答案

    阅读Reflections文档,为了查询方法注释,您应该像这样实例化Reflections:

    new Reflections("my.package", new MethodAnnotationsScanner())

    另一个选项是使用Reflections查询api

    Set<Method> set = getAllMethods(reflections.getTypesAnnotatedWith(...), withAnnotation(methodAnnotation))

    import static org.Reflections.*;

  3. # 3 楼答案

    以下是你能做的:

        final Class<?> clazz = Class.forName("com.your.SampleClass");
        final Method[] declaredMethods = clazz.getDeclaredMethods();
        for (final Method method : declaredMethods)
        {
            if (method.isAnnotationPresent(YourAnnotationClass .class))
            {
                //Do what you want
            }
        }