0

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{
}
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
  • Why don't you just make `ConsoleController` and `HttpController` extend `Controller`, instead of trying to have multiple levels of annotation? – Dawood ibn Kareem Jul 10 '22 at 19:51
  • Because, as far as I know, annotations can not have extends. If I'm mistaken with this, please do enlighten me. Another reason is that the task I've been given is to make a Spring boot clone and Spring uses this method (though it is possible they search for each separatly) – DanielDeboeverie Jul 10 '22 at 20:00
  • could you please extend your question to outline more details about what you're looking for... You say "but I'd love to just be able to add a new Controller annotation with only needing to annotate that annotation with @Controller." maybe if you could give us a code example of what that looks like as Im not entirely sure what you mean. – Michael Wiles Jul 10 '22 at 20:19
  • Changed the code to better exlain the issue. – DanielDeboeverie Jul 10 '22 at 20:59
  • Sorry, I didn't realise it wasn't possible to extend annotations. You might want to have a look at [this answer](https://stackoverflow.com/a/18585833) which seems to do something like what you're looking for. I'm not sure if it meets your needs or not. – Dawood ibn Kareem Jul 10 '22 at 21:57

0 Answers0