lundi 21 septembre 2020

Find anonymous classes by annotation

Is there a way to find anonymous classes by some annotation with some java reflection library like (Reflections)?

I have this code: it use declare a inner class (extends Object) and annotated it with @DemoAnnotation

public class DemoUsageService {

    public void doSomething() {
        this.test(new @DemoAnnotation(value="Test") Object() {
            String content = "myContent";
        });
    }
}
@Retention(RUNTIME)
public @interface DemoAnnotation {
   String value();
}

Now I want to find all (anonymous) classes in my project that are annotated with @DemoAnnotation.


I tried the Reflections Library: but it seams not to find anonymous classes (inner static classes are found).

    @Test
    public void testFindAnnotatedClasses() throws Exception {
        
        Reflections reflections = new Reflections(
                new ConfigurationBuilder()
                        .setUrls(ClasspathHelper.forPackage(DemoUsageService.class.getPackageName()))
                        .setScanners(
                                new SubTypesScanner(false),
                                new TypeAnnotationsScanner()));
        
        Set<Class<?>> result = reflections.getTypesAnnotatedWith(DemoAnnotation.class);
        assertEquals(1, result.size()); //fails, because result.size == 0
        //...
    }
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.12</version>
</dependency>




Aucun commentaire:

Enregistrer un commentaire