DanielDeboeverie
DanielDeboeverie

Reputation: 1

How do you get Java reflections to look for multiple levels of annotation

I'm trying to get multiple levels of annotation in one go. I find it kind of hard to explain in words, so let's consider the following example.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Controller
public @interface HttpController {
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Controller
public @interface ConsoleController {
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}

@Controller
public class TestOne {
}

@HttpController
public class TestTwo {
}

@ConsoleController
public class TestThree {
}

public class demo {
  public static void main(String[] args) {
    Reflections reflections = new Reflections(
       new ConfigurationBuilder()
          .setUrls(
                ClasspathHelper.forPackage(
                Demo.class.getPackageName()))
          .setScanners(new SubTypesScanner(false),
                new TypeAnnotationsScanner())
          .filterInputsBy(it ->
                it.startsWith(Demo.class.getPackageName())));

    reflections.getTypesAnnotatedWith(Controller.class).forEach(class -> 
      System.out.print(class.getSimpleName() + " ")
    )
  }
}

If you have the above class and run in the Demo class, you would get TestOne as output. I'm trying to find a way to get TestOne TestTwo TestThree as output in this situation. If I were to then add the following code, I'd have to change nothing to my Reflection code for it to work.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Controller
public @interface AnotherController{
}

@AnotherController
  public class TestFour{
}

Upvotes: 0

Views: 171

Answers (0)

Related Questions