【问题标题】:Get class methods with annotation with org.refelections使用 org.reflections 获取带有注释的类方法
【发布时间】:2012-02-15 12:17:27
【问题描述】:

我在我的项目中使用了 org.reflections (http://code.google.com/p/reflections/) 来加载带有某些注释的类。现在我上课了,我需要获取我自己制作的所有带有注释的方法。但是当我创建 Reflections 对象时,它只询问包名,所以如果我使用 getMethodsAnnotatedWith 方法,它会从给定的包类中获取所有方法,但我想从我的类中获取方法。我该怎么做?

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    你可以这样做:

        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
            }
        }
    

    【讨论】:

      【解决方案2】:

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

      重要的代码部分是:

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

      这样您将获得一组 Method 对象来使用。

      【讨论】:

        【解决方案3】:

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

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

        另一种选择是使用 Reflections 查询 api,这样,

        Set&lt;Method&gt; set = getAllMethods(reflections.getTypesAnnotatedWith(...), withAnnotation(methodAnnotation))

        import static org.Reflections.*;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-22
          • 1970-01-01
          • 2021-03-28
          • 2016-01-27
          • 1970-01-01
          相关资源
          最近更新 更多