Согласно этому сообщению это вы должны попробовать:
Java7:
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
Greeter greetings = Greetings.class.getAnnotation(Greeter.class);
System.out.println("Hello there, " + greetings.greet() + " !!");
GreeterByHand greetingsByHand = Greetings.class.getAnnotation(GreeterByHand.class);
System.out.println("Hello there, " + greetingsByHand.greet() + " !!");
addAnnotationManually(GreeterByHand.class, instanceOfGreeterByHand("Yayy added by hand"), Greetings.class);
Greeter greetingsAgain = Greetings.class.getAnnotation(Greeter.class);
System.out.println("Hello there, " + greetingsAgain.greet() + " !!");
GreeterByHand greetingsByHandAgain = Greetings.class.getAnnotation(GreeterByHand.class);
System.out.println("Hello there, " + greetingsByHandAgain.greet() + " !!");
}
private static void addAnnotationManually(Class<? extends Annotation> targetAnnotation, Annotation annotationInstance, Class<Greetings> targetClass) throws Exception {
Field annotationsField = Class.class.getDeclaredField("annotations");
annotationsField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Class<? extends Annotation>, Annotation> originalAnnotations = (HashMap<Class<? extends Annotation>, Annotation>) annotationsField.get(targetClass);
originalAnnotations.put(targetAnnotation, annotationInstance);
}
public static GreeterByHand instanceOfGreeterByHand(final String greet) {
return new GreeterByHand() {
@Override
public String greet() {
return greet;
}
@Override
public Class<? extends Annotation> annotationType() {
return GreeterByHand.class;
}
};
}
}
(я не знаю, почему вы хотите это сделать, я думаю,за вашим кодом есть некоторый антипаттерн)
Привет:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Greeter {
String greet() default "";
}
GreeterByHand:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface GreeterByHand {
String greet() default "";
}
Привет:
@Greeter(greet="Good morning")
@GreeterByHand
public class Greetings {}