mercredi 20 novembre 2019

Change annotation of a class field dynamically at runtime

Suppose I have a class definition

@DynamoDBTable(tableName = "table_one")
public class ProcessedVideoItem {
        @DynamoDBHashKey(attributeName = "hash_key")
        private String id;
}

How can I dynamically change the atributeName in @DynamoDBHashKey annotation at runtime to something else like actual_hash_key

I have found the solution to change the annotation on class at runtime :

void setAnnotationN(Class< ? > clazzToLookFor, Class<? extends Annotation> annotationToAlter){
    Method method = Class.class.getDeclaredMethod("annotationData", null);
    method.setAccessible(true);            
    Object annotationData = method.invoke(clazzToLookFor);
    Field annotations = annotationData.getClass().getDeclaredField("annotations");
    annotations.setAccessible(true);
    Map<Class<? extends Annotation>, Annotation> map =
                 (Map<Class<? extends Annotation>, Annotation>)annotations.get(annotationData);
    map.put(annotationToAlter, annotationValue);
}

But this does not work for annotation on a field of a class. I tried changing

Object annotationData = method.invoke(clazzToLookFor.getDeclaredField("id"));

But this is not working.





Aucun commentaire:

Enregistrer un commentaire