javassist中如何判断一个字段的类型是Map还是Collection

How to judge the type of a field is a Map or a Collection in javassist

我使用javassist生成代码。

现在我需要找到实现Map或Collection(Set或List)的字段,我在javassist教程中找不到关键,怎么办?非常感谢!

基本上,您必须遍历所有字段,获取每个字段类型的所有超级 类 和接口,并检查您需要的类型。

package hello;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.NotFoundException;

import java.util.*;
import java.util.stream.Collectors;

class Test {
    public ArrayList arrayList;
    public List list;
    public HashSet hashSet;
    public Set set;
    public HashMap hashMap;
    public Map map;
    public Object object;
}

class Main {
    public static void main(String[] args) throws Exception {
        CtClass testClass = ClassPool.getDefault().get("hello.Test");

        for (CtField ctField : testClass.getFields()) {
            CtClass type = ctField.getType();

            Set<String> allSupper = getAllSuperclasses(type)
                    .stream()
                    .map(CtClass::getName)
                    .collect(Collectors.toSet());

            if (allSupper.contains(Map.class.getCanonicalName())){
                System.out.format("field %s is a Map\n", ctField.getName());
            }

            if (allSupper.contains(Collection.class.getCanonicalName())){
                System.out.format("field %s is a Collection\n", ctField.getName());
            }
        }
    }

    private static Set<CtClass> getAllSuperclasses(CtClass ctClass) throws NotFoundException {
        HashSet<CtClass> ctClasses = new HashSet<>();

        while (ctClass != null){
            ctClasses.add(ctClass);
            CtClass[] interfaces = ctClass.getInterfaces();
            Collections.addAll(ctClasses, interfaces);
            ctClass = ctClass.getSuperclass();
        }

        return ctClasses;
    }
}

将打印

field arrayList is a Collection
field list is a Collection
field hashSet is a Collection
field set is a Collection
field hashMap is a Map
field map is a Map