how find fields of all member variables contained in java bean

帅比萌擦擦* 提交于 2019-12-04 19:49:26

It's kind of a pain but you have to go in two dimensions

yourBeanClass.getSuperclass(); (and recursively get all superclasses until Object)

and then you can get the fields of each one

eachClass.getDeclaredFields() NOT getFields so you can get all the private fields

Once you have each field

field.getType() which returns the Class of that field

then of course, you need to go up that dudes superclass chain again to make sure you get ALL the fields of the class including the ones in the superclass

Once you have that chain of classes for that field, you can then get it's fields by repeating the above....yes, the jdk made this fun!!!! I wish to god they had a getAllDeclaredFields method so I didn't have to go up the superclass heirarchy.

IMPORTANT: you need to call field.setAccessible(true) so you can read and write to it when it is a private field by the way!!!

Here is code that gets all the fields for a Class including the superclasses..

private static List<Field> findAllFields(Class<?> metaClass) {
    List<Field[]> fields = new ArrayList<Field[]>();
    findFields(metaClass, fields);

    List<Field> allFields = new ArrayList<Field>();
    for(Field[] f : fields) {
        List<Field> asList = Arrays.asList(f);
        allFields.addAll(asList);
    }
    return allFields;
}

private static void findFields(Class metaClass2, List<Field[]> fields) {
    Class next = metaClass2;
    while(true) {
        Field[] f = next.getDeclaredFields();
        fields.add(f);
        next = next.getSuperclass();
        if(next.equals(Object.class))
            return;
    }
}

later, Dean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!