mercredi 19 janvier 2022

Get passed Annotation Parameters from Field Annotations

I have two annotations, this class one:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Processor {
  public String description() default "";
}

And also this Field one:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ProcessorParameter {
    public String name() default "";
    public String value() default "";
    public String[] range() default {};
    public String description() default "";
}

They both are getting used in a class like this one:

    @Processor(description = "blabla")
    public class Prozessor1{
        @ProcessorParameter(description = "test3")
        public int parameter1;
        @ProcessorParameter(description = "test4")
        public int parameter2;
        @ProcessorParameter(description = "test5")
        public int parameter3;
    }

I have different classes of the Prozessor and I want to be able to access all the parameters of the Prozessor and ProcessorParameter Annotation.

Right now I am using this code:

public static void main(String[] args) {
        Reflections ref = new Reflections();
        for (Class<?> cl:
                ref.getTypesAnnotatedWith(Processor.class)){
            Processor processor = cl.getAnnotation(Processor.class);
            System.out.printf("Found class: %s, with meta name: %s%n",
                    cl.getSimpleName(),processor.description());
            for(Field field : cl.getFields()) {
                System.out.printf("Found parameter: %s and %s%n",
                        field.getName(), field.getName());
            }
        }
    }

Right now I am getting this as a result:

Found class: Prozessor1, with meta name: blabla
Found parameter: parameter1 and parameter1
Found parameter: parameter2 and parameter2
Found parameter: parameter3 and parameter3

I obviously do not need the second field.getName() but I want to access the passed ProcessorParameter description ("test3"/"test4"/"test5") but I do not know how to access this.





Aucun commentaire:

Enregistrer un commentaire