All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.taobao.arthas.bytekit.utils.AsmAnnotationUtils Maven / Gradle / Ivy

package com.taobao.arthas.bytekit.utils;

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

import com.alibaba.arthas.deps.org.objectweb.asm.tree.AnnotationNode;

/**
 * 
 * @author hengyunabc 2020-05-04
 *
 */
public class AsmAnnotationUtils {

    public static List queryAnnotationInfo(List annotations, String annotationType,
            String key) {
        List result = new ArrayList();
        if (annotations != null) {
            for (AnnotationNode annotationNode : annotations) {
                if (annotationNode.desc.equals(annotationType)) {
                    if (annotationNode.values != null) {
                        Iterator iterator = annotationNode.values.iterator();
                        while (iterator.hasNext()) {
                            String name = (String) iterator.next();
                            Object values = iterator.next();
                            if (key.equals(name)) {
                                result.addAll((List) values);
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    public static void addAnnotationInfo(List annotations, String annotationType, String key,
            String value) {

        AnnotationNode annotationNode = null;
        for (AnnotationNode tmp : annotations) {
            if (tmp.desc.equals(annotationType)) {
                annotationNode = tmp;
            }
        }

        if (annotationNode == null) {
            annotationNode = new AnnotationNode(annotationType);
            annotations.add(annotationNode);
        }

        if (annotationNode.values == null) {
            annotationNode.values = new ArrayList();
        }

        // 查找有没有对应的key
        String name = null;
        List values = null;
        Iterator iterator = annotationNode.values.iterator();
        while (iterator.hasNext()) {
            if (key.equals(iterator.next())) {
                values = (List) iterator.next();
            } else {
                iterator.next();
            }
        }
        if (values == null) {
            values = new ArrayList();
            annotationNode.values.add(key);
            annotationNode.values.add(values);
        }
        if (!values.contains(values)) {
            values.add(value);
        }
    }
}