0

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.

Shriyansh Gautam
  • 1,084
  • 1
  • 7
  • 13
  • They're not meant to be changed at runtime. – Kayaman Nov 20 '19 at 13:34
  • Possible duplicate of [Modify a method annotation parameter at runtime](https://stackoverflow.com/questions/27697358/modify-a-method-annotation-parameter-at-runtime) – GotoFinal Nov 20 '19 at 13:40
  • same as for a method https://stackoverflow.com/questions/27697358/modify-a-method-annotation-parameter-at-runtime but note that library that is reading these annotation might read and remember this value so you need to be sure that your code will edit it first – GotoFinal Nov 20 '19 at 13:40

0 Answers0