jeudi 11 avril 2019

Add String into List

I'm trying to get a list of all the fields in my classes with Reflection. I'm having trouble with passing List as simply String though. My code to get the fields right now is:

private static List<Field> getFields(Class<?> i, List<Field> result) throws Exception {
        while (i != null && i != Object.class) {
            for (Field field : i.getDeclaredFields()) {
                if (!field.isSynthetic()) {
                    if (!List.class.isAssignableFrom(field.getType())) {
                        if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
                            result.add(field);
                        }
                    } else if (List.class.isAssignableFrom(field.getType())) {
                        Field stringListField = i.getDeclaredField(field.getName());
                        ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
                        Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
                        if (stringListClass.getSimpleName().equals("String")) {
                            result.add(field);
                        } else {
                            getFields(stringListClass, result);
                        }
                    }
                }
            }
            i = i.getSuperclass();
        }
        return result;
    }

The output of this is:

LIST,STRING,STRING,STRING,STRING,STRING

But what I need to get is:

STRING,STRING,STRING,STRING,STRING,STRING

How would I edit:

if (stringListClass.getSimpleName().equals("String")) {
   .add(field);
{
   getFields(stringListClass, result);
}

so that the field would be treated as String and not List?





Aucun commentaire:

Enregistrer un commentaire