ASM4 读取java注解 - 优化版

package hello.asm.my.readAnnotaion;

import java.util.ArrayList;
import java.util.List;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AnnotationNode;

public class ClassVisitorAnnotaion extends ClassVisitor{
    private List<AnnotationNode> tableAnnotaionList = new ArrayList<AnnotationNode>();
    private List<AnnotationNode> fieldAnnotaionList = new ArrayList<AnnotationNode>();
    
    public ClassVisitorAnnotaion(int api) {
	super(api);
    }
    
    @Override
    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
	AnnotationNode node = new AnnotationNode(desc);
	tableAnnotaionList.add(node);
        return node;
    }
    
    @Override
    public FieldVisitor visitField(int access, String name, String desc,
            String signature, Object value) {
	return new FieldVisitor(Opcodes.ASM4) {
	    @Override
	    public AnnotationVisitor visitAnnotation(String desc,boolean visible) {
	        AnnotationNode node = new AnnotationNode(desc);
	        fieldAnnotaionList.add(node);
	        return node;
	    }
	};
    }

    public List<AnnotationNode> getTableAnnotaionList() {
        return tableAnnotaionList;
    }
    public void setTableAnnotaionList(List<AnnotationNode> tableAnnotaionList) {
        this.tableAnnotaionList = tableAnnotaionList;
    }

    public List<AnnotationNode> getFieldAnnotaionList() {
        return fieldAnnotaionList;
    }
    public void setFieldAnnotaionList(List<AnnotationNode> fieldAnnotaionList) {
        this.fieldAnnotaionList = fieldAnnotaionList;
    }
}

public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, IOException {
	    String n = User.class.getName();
	    ClassReader cr = new ClassReader(n);
	    ClassVisitorAnnotaion annotaion = new ClassVisitorAnnotaion(ASM4);
	    cr.accept(annotaion, ClassReader.SKIP_CODE);
	    
	    List<AnnotationNode> tableANodes = annotaion.getTableAnnotaionList();
	    List<AnnotationNode> fieldAnodes = annotaion.getFieldAnnotaionList();
	    for (AnnotationNode tANode : tableANodes) {
		System.out.println(tANode.values.get(0) + " : " + tANode.values.get(1));
	    }
	    for (AnnotationNode fANode : fieldAnodes) {
		System.out.println(fANode.values.get(0) + " : " + fANode.values.get(1));
	    }
	}


你可能感兴趣的:(ASM4 读取java注解 - 优化版)