如何在运行时向字段添加注释或任何其他标记?

时间:2018-12-19 10:28:16

标签: java reflection

我正在使用Java Reflection API从另一个对象创建一个对象。 在源对象的类上定义了一个注释。但是,它没有在目标对象的类上定义。

我知道不可能在运行时动态添加任何注释。 另外,也无法使用Javassist,因为这些类已经到了时候。

在运行时是否可以将批注的值复制到目标对象?不必使用注释。

1 个答案:

答案 0 :(得分:0)

根据此帖子this,您应该尝试:

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 {}