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?
getField can get a field inherited from a superclass but getDeclaredField cannot. getDeclaredField restrict itself to the class you call the function on.
The only way we have to get only inherited fields is to use the getDeclaredFields() method, as we just did, and filter its results using the Field::getModifiers method. This one returns an int representing the modifiers of the current field. Each possible modifier is assigned a power of two between 2^0 and 2^7.
getField() returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired field.
Field. get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.
Use this.getClass().getDeclaredFields().length
The getFields
method is for accessible public fields - see documentation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With