Thomas Darimont
Erfahrenes Mitglied
Hallo!
here is another funny hack
Ausgabe:
Gruß Tom
here is another funny hack

Java:
package de.tutorials.training;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
public class AnnotationValueChangeExample {
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.getClass().isAnnotationPresent(SomeAnnotation.class));
SomeAnnotation someAnnotation = foo.getClass().getAnnotation(SomeAnnotation.class);
System.out.println(someAnnotation);
changeValuesOfAnnotation(someAnnotation, new HashMap<String, String>(){{put("value", "Test2");}});
System.out.println(foo.getClass().getAnnotation(SomeAnnotation.class));
}
private static void changeValuesOfAnnotation(
Object someAnnotation,
Map<String, String> newValues) {
if (Proxy.isProxyClass(someAnnotation.getClass())) {
Object invocationHandler = Proxy.getInvocationHandler(someAnnotation);
try {
Field field = invocationHandler.getClass().getDeclaredField("memberValues");
field.setAccessible(true);
field.set(invocationHandler, newValues);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@SomeAnnotation("Test")
static class Foo {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
static @interface SomeAnnotation {
String value();
}
}
Ausgabe:
Code:
true
@de.tutorials.training.AnnotationValueChangeExample$SomeAnnotation(value=Test)
@de.tutorials.training.AnnotationValueChangeExample$SomeAnnotation(value=Test2)
Gruß Tom