Get all variable names in a class
Solution 1:
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.
Solution 2:
https://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html also has charts for locating methods and constructors.
Solution 3:
You can use any of the two based on your need:
Field[] fields = ClassName.class.getFields(); // returns inherited members but not private members.
Field[] fields = ClassName.class.getDeclaredFields(); // returns all members including private members but not inherited members.
To filter only the public fields from the above list (based on requirement) use below code:
List<Field> fieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPublic(field.getModifiers())).collect(
Collectors.toList());