This question already has an answer here:
-
java reflection getFields for private member| accessing object name value dynamically
2 answers
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?
Use this.getClass().getDeclaredFields().length
The getFields
method is for accessible public fields - see documentation.
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.
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.