Get all variable names in a class

JavaReflection

Java Problem Overview


I have a class and I want to find all of its public fields (not methods). How can I do this?

Java Solutions


Solution 1 - Java

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 http://java.sun.com/javase/6/docs/api/java/lang/Class.html">`java.lang.Class`</a>;. Check its docs for more interesting reflection methods.

The Field class above is http://java.sun.com/javase/6/docs/api/java/lang/reflect/Field.html">`java.lang.reflect.Field`</a>;. You may take a look at the whole http://java.sun.com/javase/6/docs/api/java/lang/reflect/package-summary.html">`java.lang.reflect`</a> package.

Solution 2 - Java

https://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html also has charts for locating methods and constructors.

enter image description here

Solution 3 - Java

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());

Solution 4 - Java

As mentioned by few users, below code can help find all the fields in a given class.

TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
    String name=method.getName();
    if(name.startsWith("get"))
    {
        System.out.println(name.substring(3));
    }else if(name.startsWith("is"))
    {
        System.out.println(name.substring(2));
    }
}

However a more interesting approach is below:

With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)

TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();

Map<String,Object> props = m.convertValue(testObject, Map.class);

for(Map.Entry<String, Object> entry : props.entrySet()){
    if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
        System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionufkView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavacellepoView Answer on Stackoverflow
Solution 3 - JavaSahil ChhabraView Answer on Stackoverflow
Solution 4 - JavaAmit KaneriaView Answer on Stackoverflow