|
| 1 | +package com.baeldung.java.reflection; |
| 2 | + |
| 3 | +import java.lang.annotation.Annotation; |
| 4 | +import java.lang.reflect.Field; |
| 5 | +import java.lang.reflect.Method; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +public class GreetingAnnotation { |
| 9 | + |
| 10 | + private static final String ANNOTATION_METHOD = "annotationData"; |
| 11 | + private static final String ANNOTATION_FIELDS = "declaredAnnotations"; |
| 12 | + private static final String ANNOTATIONS = "annotations"; |
| 13 | + |
| 14 | + public static void main(String ...args) { |
| 15 | + Greeter greetings = Greetings.class.getAnnotation(Greeter.class); |
| 16 | + System.err.println("Hello there, " + greetings.greet() + " !!"); |
| 17 | + |
| 18 | + Greeter targetValue = new DynamicGreeter("Good evening"); |
| 19 | + //alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue); |
| 20 | + alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue); |
| 21 | + |
| 22 | + greetings = Greetings.class.getAnnotation(Greeter.class); |
| 23 | + System.err.println("Hello there, " + greetings.greet() + " !!"); |
| 24 | + } |
| 25 | + |
| 26 | + @SuppressWarnings("unchecked") |
| 27 | + public static void alterAnnotationValueJDK8(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) { |
| 28 | + try { |
| 29 | + Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null); |
| 30 | + method.setAccessible(true); |
| 31 | + |
| 32 | + Object annotationData = method.invoke(targetClass); |
| 33 | + |
| 34 | + Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS); |
| 35 | + annotations.setAccessible(true); |
| 36 | + |
| 37 | + Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData); |
| 38 | + map.put(targetAnnotation, targetValue); |
| 39 | + } catch (Exception e) { |
| 40 | + e.printStackTrace(); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + @SuppressWarnings("unchecked") |
| 45 | + public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) { |
| 46 | + try { |
| 47 | + Field annotations = Class.class.getDeclaredField(ANNOTATIONS); |
| 48 | + annotations.setAccessible(true); |
| 49 | + |
| 50 | + Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass); |
| 51 | + System.out.println(map); |
| 52 | + map.put(targetAnnotation, targetValue); |
| 53 | + System.out.println(map); |
| 54 | + } catch (Exception e) { |
| 55 | + e.printStackTrace(); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments