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

427 views Asked by At

I use javassist to generate code.

Now I need to find the field which implement Map or Collection(Set or List), I can not find the key in javassist tutorial, how to do it? Thanks very much!

1

There are 1 answers

0
light_keeper On BEST ANSWER

Basically, you have to iterate over all fields, get all super classes and interfaces of each field type and check for types you need.

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;
    }
}

will print

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