mardi 4 septembre 2018

Changing custom annotation implementation with multiple fields at runtime in java 7

I need to change one of the custom annotation field at Runtime (Java 7) from another class. As its not a problem to access the annotation field for given method, a cannot discover how to change value of fields in annotation (if its possible).

I have such implementation of annotation:

@Target({ElementType.METHOD}) 
@Retention(RUNTIME)
public @interface Something {

public String description() default "";

public boolean required() default false;

public int sortOrder() default -1;

}

In java class XYZ I have annotated many methods and define annotation fields such as:

@Something(description="name",required=true, sortOrder=1)
String getName();
void setName(String name);

@Something(description="address",required=true, sortOrder=1)
String getAddress();
void setAddress(String address); 

Finally, in another class I need to change some values of annotation for annotated method in certain conditions, for example required from true to false for method getAddress(). I grab annotation data like this:

    try{
        Method method = XYZ.class.getDeclaredMethod("getAddress", null);
        method.setAccessible(true);
        Something ann = method.getAnnotation(Something.class);
        String name = ann.description();

    } catch (Exception e) {
        e.printStackTrace();
    }

I stuck with this as found how to change value for annotations with only one field.

PS. Sorry for my English...





Aucun commentaire:

Enregistrer un commentaire