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

北城以北 提交于 2019-12-30 08:12:03

问题


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.



来源:https://stackoverflow.com/questions/16464392/this-getclass-getfields-length-always-returns-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!