How to check if a field of CtClass is of type collection in Java

53 Views Asked by At

I am trying to list down variables inside my jar file using javaassit. I want to check if the field in a class file is of type collection. I am using "Collection.class.isAssignableForm", but it does not work because field.getType().getCLass() returns class as CtCLassType. Is there a way to check if a CtClass field is of type Collection ? In the similar way how to check if that field type is Serializable ?

CtClass loClass = ClassPool.getDefault().get(lsClassName);
CtField[] loFields = loClass.getDeclaredFields();
// iterate over fields
for(CtField field: loFields){
  // this does not work
  Collection.class.isAssignableForm(field.getType().getCLass());
}

Any help is much appreciated.

2

There are 2 best solutions below

1
王大拿 On

try to convert it into a Class first?

Class clazz = loClass.toClass();
Field[] loFields = clazz.getDeclaredFields();
...
1
Easterwood On

The CtClass is an abstract representation of the "real" classes and that's way you can't assume that the container class of the original field is assignable to a java.util.Collection.

The javassist tutorial shows a way to get to the "real" class. But there is a drawback described in the javadoc: Converts this class to a java.lang.Class object. Once this method is called, further modifications are not allowed any more...... If you want to change the class afterwards this maybe isn't a solution for your problem.