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

2019-02-16 21:55发布

问题:

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?

回答1:

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



回答2:

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.



回答3:

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.