13

I am trying to get the number of fields in a particular class. However the technique I am using is not working and always returns 0:

this.getClass().getFields().length;

How do I get the field count of a particular class?

4

3 回答 3

28

Use this.getClass().getDeclaredFields().length The getFields method is for accessible public fields - see documentation.

于 2013-05-09T14:38:54.217 回答
2

From the Class#getFields JavaDoc:

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

Maybe your fields are declared as private or protected, thus never getting the right number of fields in your class. You should use Class#getDeclaredFields

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

于 2013-05-09T14:40:18.240 回答
1

getFields() only returns publicly accessible fields. Chances are, your class' fields are wrapped by getters and setters.

You would want to use getDeclaredFields() instead. It will return all fields, regardless of visibility.

于 2013-05-09T14:42:19.023 回答