Search code examples
javaspringreflectionannotations

Given a class, find out if it has been annotated with any annotation, yes or no


My tutor has given me this task to write a Boolean method that checks whether a class has been annotated at all. Don't want to bother you guys with further details, but it was actually a package, so at first I used the Google reflections library to collect all classes from my project. Unfortunately, this library, along with others doesn't answer my question, they all require me to provide annotation class, which I yet to find out with my method I am struggling with.

Edit: this is a Spring project


Solution

  • a Boolean method

    I doubt that. I think they want you to write a boolean method. Boolean is the wrapper type. It's a tri-state thing you don't want (it can be null, true, or false. Yich).

    so at first I used the Google reflections library to collect all classes from my project.

    That seems completely unrelated to the question.

    All you need is:

    Class<?> toCheck = ...;
    return toCheck.getAnnotations().length > 0;
    

    Note that annotations need to mention whether they are visible at runtime or not. If they aren't, that won't work, but the point is, nothing will (the 'point' of an annotation that doesn't have a retention level of source is that you can't tell at runtime whether it is there, after all).