I have a class and I want to find all of its public fields (not methods). How can I do this?
Field[] fields = YourClassName. class. getFields(); returns an array of all public variables of the class.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
The name of the variable should begin with either alphabet or, an underscore (_) or, a dollar ($) sign. The identifiers used for variables must not be keywords. No spaces or special characters are allowed in the variable names of Java. Variable names may contain 0 to 9 numbers (if not at the beginning).
In JavaSW, it's easy to list the declared fields of a class. If you have an object, you can obtain its Class object by calling getClass() on the object. You can then call getDeclaredFields() on the Class object, which will return an array of Field objects. This list can include public, protected, and private fields.
Field[] fields = YourClassName.class.getFields();
returns an array of all public variables of the class.
getFields()
return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields()
, and filter the public
ones with the following Modifier
approach:
Modifier.isPublic(field.getModifiers());
The YourClassName.class
literal actually represents an object of type java.lang.Class
. Check its docs for more interesting reflection methods.
The Field
class above is java.lang.reflect.Field
. You may take a look at the whole java.lang.reflect
package.
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