Java reflection get all private fields

后端 未结 6 780
北恋
北恋 2020-12-07 22:29

I wonder is there a way to get all private fields of some class in java and their type.

For example lets suppose I have a class

class SomeClass {
            


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-07 22:49

    It is possible to obtain all fields with the method getDeclaredFields() of Class. Then you have to check the modifier of each fields to find the private ones:

    List privateFields = new ArrayList<>();
    Field[] allFields = SomeClass.class.getDeclaredFields();
    for (Field field : allFields) {
        if (Modifier.isPrivate(field.getModifiers())) {
            privateFields.add(field);
        }
    }
    

    Note that getDeclaredFields() will not return inherited fields.

    Eventually, you get the type of the fields with the method Field.getType().

提交回复
热议问题