【问题标题】:How to list all methods annotated with specific annotation in "src/test" path using Reflections?如何使用反射在“src/test”路径中列出所有带有特定注释的方法?
【发布时间】:2019-07-16 17:22:56
【问题描述】:

我有两个注解:@Feature 和@Scenario。

我在控制器方法中使用的@Feature 注释(GET/PUT/POST... 在路径“src/main/java...”中)。

我在单元测试中使用的@Scenario 注释(路径“src/test/java...”中的控制器或服务测试)。

我需要列出使用这两个注解进行注解的所有方法,因此我在“src/main/java...”路径中创建了一个类来执行此操作。 我能够找到所有用@Feature 注释的方法,但我找不到用@Scenario 注释的方法。 我该怎么做?

我尝试使用 Reflections 库来做到这一点

final Set<Method> features = new Reflections("com.myprefix", new MethodAnnotationsScanner()).getMethodsAnnotatedWith(Feature.class);
final Set<Method> scenarios = new Reflections("com.myprefix", new MethodAnnotationsScanner()).getMethodsAnnotatedWith(Scenario.class);

“features”返回所有带有@Feature注解的方法,但“scenarios”返回空

【问题讨论】:

    标签: java annotations


    【解决方案1】:

    您是否尝试过编写 JUnit 测试来解决您的问题?这是一个可以解决您的问题的方法:

    @Test
    public void findMethodsannotatedWith(){
        List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
        classLoadersList.add(ClasspathHelper.contextClassLoader());
        classLoadersList.add(ClasspathHelper.staticClassLoader());
    
        Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()
                , new MethodAnnotationsScanner())
            .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.myprefix"))));
    
        final Set<Method> features = reflections.getMethodsAnnotatedWith(Feature.class);
        final Set<Method> scenarios = reflections.getMethodsAnnotatedWith(Scenario.class);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多