Java reflection get all private fields

user2152361 picture user2152361 · Mar 9, 2013 · Viewed 72.3k times · Source

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 {
    private String aaa;
    private SomeOtherClass bbb;
    private double ccc;
}

Now I would like to get all private fields (aaa, bbb, ccc) of class SomeClass (Without knowing name of all fields upfront) and check their type.

Answer

Cyrille Ka picture Cyrille Ka · Mar 9, 2013

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<Field> 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().