mercredi 18 janvier 2023

Problems in changing value of a runtime annotation with reflection (Java 17)

I'm stuck into trying to change the value of a @Retention(RetentionPolicy.RUNTIME) annotation with Java 17. I think my code has some problems also related to the Java 9 illegal reflective access.

That's what I've tried, but it doesn't work:

public static void changeAnnotationValue(String value) {
        Greeter oldAnnotation = Greetings.class.getAnnotation(Greeter.class);
        Greeter newAnnotation = new Greeter() {

            @Override
            public Class<? extends Annotation> annotationType() {
                return oldAnnotation.annotationType();
            }

            @Override
            public String value() {
                return value;
            }
        };
        try {
            Method method = Greetings.class.getDeclaredMethod("annotationData", null);
            method.setAccessible(true);

            Field annotations = method.getClass().getDeclaredField("annotations");
            annotations.setAccessible(true);

            Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(method);
            map.put(Greeter.class, newAnnotation);
        } catch (NoSuchMethodException | IllegalAccessException | NoSuchFieldException e) {
            //Handle exceptions
            e.printStackTrace();
        }
    }




Aucun commentaire:

Enregistrer un commentaire