0

I am playing around Annotation in java. I am using reflection to get the values in the annotated values at runtime. Below is how I am using reflection to get all the annotated variables and their values.

Reflections reflections = new Reflections(".*");
Set<Class<?>> flagAnnotatedClasses =
    new HashSet<Class<?>>() {
      {
        addAll(reflections.getTypesAnnotatedWith(Flag.class));
      }
    };
for (Class cl : flagAnnotatedClasses) {
  // Get all the flags for a particular class annotated with @Flag.
  Annotation[] flags = cl.getAnnotationsByType(Flag.class);
  for (Annotation flag : flags) {
    String name = ((Flag) flag).name();
    String value = ((Flag) flag).value();
    System.out.println("name = " + name + ", value = " + value);
  }
}

It is working fine, except that during compiling, it gives me the warning:

Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

So, I ran it with -Xlint:unchecked and I got below warning message:

warning: [unchecked] unchecked call to <A>getAnnotationsByType(Class<A>) as a member of the raw type Class
      Annotation[] flags = cl.getAnnotationsByType(Flag.class);
                                                  ^
  where A is a type-variable:
    A extends Annotation declared in method <A>getAnnotationsByType(Class<A>)

How could I get rid of this warning?

Ankit Shubham
  • 2,989
  • 2
  • 36
  • 61
  • 3
    change `Class cl` to `Class> cl` – Lino Mar 21 '19 at 09:34
  • 1
    I also suggest reading: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Lino Mar 21 '19 at 09:37
  • 1
    Also if you change it to Class> you will be able to use `Flag[]` instead of `Annotation` and remove that cast in loop. – GotoFinal Mar 21 '19 at 13:43
  • Worst use of the [double brace initialisation anti-pattern](https://stackoverflow.com/a/27521360/2711488) ever. A plain `Set> flagAnnotatedClasses = new HashSet<>(reflections.getTypesAnnotatedWith(Flag.class));` would do, though, it’s not clear why you make a copy at all. What’s wrong with iterating over the result of `reflections.getTypesAnnotatedWith(Flag.class)` directly? – Holger Mar 22 '19 at 10:27

0 Answers0