Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.getClass().getFields().length; always returns 0 [duplicate]

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?

like image 964
Roy Hinkley Avatar asked May 09 '13 14:05

Roy Hinkley


People also ask

What is difference between getField and getDeclaredField?

getField can get a field inherited from a superclass but getDeclaredField cannot. getDeclaredField restrict itself to the class you call the function on.

How do you inherit fields using Reflection?

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.

What is getField?

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.

How do you find the value of 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.


2 Answers

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

like image 187
Mena Avatar answered Sep 18 '22 14:09

Mena


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.

like image 22
Luiggi Mendoza Avatar answered Sep 17 '22 14:09

Luiggi Mendoza