package com.docus.server.collect.web.utils;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ConstPool;
import javassist.bytecode.FieldInfo;
import javassist.bytecode.annotation.Annotation;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

@Slf4j
public class DynamicAnnotation {


    /**
     * 功能，动态的给类属性添加注解
     *
     * @param className 类名
     * @param attributeName 类属性
     * @param typeName 注解类型
     */
    public static void addAnnotation(String className, String attributeName, String typeName) {
        try {
            ClassPool pool = ClassPool.getDefault();
            CtClass ct = pool.get(className);
            CtField cf = ct.getField(attributeName);
            FieldInfo fieldInfo = cf.getFieldInfo();
            AnnotationsAttribute attribute = (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
            ConstPool cp = fieldInfo.getConstPool();
            Annotation annotation = new Annotation(typeName, cp);
            System.out.println(annotation);
            attribute.addAnnotation(annotation);
            System.out.println(Arrays.toString(attribute.getAnnotations()));
        } catch (NotFoundException e) {
            log.error("此类不存在", e);
        }
    }
}
