Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Test2
- {
- public static void main(String[] args) throws Exception
- {
- // editing method annotations
- {
- Method targetMethod = Test2.class.getDeclaredMethod("foobar");
- final Something oldAnnotation = (Something) targetMethod.getAnnotations()[0];
- System.out.println("oldAnnotation = " + oldAnnotation.someProperty());
- Annotation newAnnotation = new Something()
- {
- @Override
- public String someProperty()
- {
- return "value2";
- }
- @Override
- public Class<? extends Annotation> annotationType()
- {
- return oldAnnotation.annotationType();
- }
- };
- Class<?> executableClass = Class.forName("java.lang.reflect.Executable");
- Field field = executableClass.getDeclaredField("declaredAnnotations");
- field.setAccessible(true);
- Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) field.get(targetMethod);
- System.out.println(annotations.get(Something.class));
- annotations.put(Something.class, newAnnotation);
- System.out.println(annotations.get(Something.class));
- //targetMethod = Test2.class.getDeclaredMethod("foobar");
- Something modifiedAnnotation = (Something) targetMethod.getAnnotations()[0];
- System.out.println("modifiedAnnotation = " + modifiedAnnotation.someProperty());
- }
- // editing class annotations
- System.out.println("====");
- {
- final Something oldAnnotation = (Something) Foobar.class.getAnnotations()[0];
- System.out.println("oldAnnotation = " + oldAnnotation.someProperty());
- Annotation newAnnotation = new Something()
- {
- @Override
- public String someProperty()
- {
- return "another value";
- }
- @Override
- public Class<? extends Annotation> annotationType()
- {
- return oldAnnotation.annotationType();
- }
- };
- Method method = Class.class.getDeclaredMethod("getDeclaredAnnotationMap");
- method.setAccessible(true);
- Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) method.invoke(Foobar.class);
- annotations.put(Something.class, newAnnotation);
- Something modifiedAnnotation = (Something) Foobar.class.getAnnotations()[0];
- System.out.println("modifiedAnnotation = " + modifiedAnnotation.someProperty());
- }
- }
- @Something(someProperty = "some value")
- public static class Foobar
- {
- }
- @Something(someProperty = "value1")
- public static void foobar()
- {
- }
- @Retention(RetentionPolicy.RUNTIME)
- @interface Something
- {
- String someProperty();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement