javassist給方法添加注解

HazelB29 8年前發布 | 2K 次閱讀 Java javassist
package cn.outofmemory.hello.javassist;

import javassist.*;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.IntegerMemberValue;

import java.io.IOException;

/**
 * add annotation with javassist
 * Created by outofmemory.cn on 2015/12/14.
 */
public class App {
    public static void main(String[] args) throws CannotCompileException, IOException {
        ClassPool pool = ClassPool.getDefault();

        // create the class
        CtClass cc = pool.makeClass("foo");
        ClassFile ccFile = cc.getClassFile();
        ConstPool constpool = ccFile.getConstPool();

        // create the annotation
        AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
        Annotation annot = new Annotation("MyAnnotation", constpool);
        annot.addMemberValue("value", new IntegerMemberValue(ccFile.getConstPool(), 0));
        attr.addAnnotation(annot);

        // create the method
        CtMethod mthd = CtNewMethod.make("public Integer getInteger() { return null; }", cc);
        cc.addMethod(mthd);
        mthd.getMethodInfo().addAttribute(attr);

        cc.writeFile("./");
        // generate the class
        Class<?> clazz = cc.toClass();

        // length is zero
        java.lang.annotation.Annotation[] annots = clazz.getAnnotations();
    }
}
 本文由用戶 HazelB29 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!