Is this the right way to retrieve all the fields from any Object? I have a method that returns a List&lt;Object&gt; from any given Object containing its values. It doesn't get the values of any static or final field in the class.

public List&lt;Object&gt; objectData(Object object) {
    Field[] fields = object.getClass().getDeclaredFields();
    Set&lt;String&gt; realFields = new LinkedHashSet&lt;String&gt;();
    for(Field field : fields) {
        if (!(java.lang.reflect.Modifier.isStatic(field.getModifiers()) ||
              java.lang.reflect.Modifier.isFinal(field.getModifiers()))) {
            realFields.add(field.getName());
        }
    }
    List&lt;Object&gt; row = new ArrayList&lt;Object&gt;();
    for(String realField : realFields) {
        Field currentField = object.getClass().getDeclaredField(realField);
        currentField.setAccessible(true);
        row.add(currentField.get(object));
    }
    return row;
}


Is this the right approach? Isn't something else I can be missing?



EDIT: The method above was adapted from this one. I'm assuming Collection&lt;T&gt; data is a valid non-empty collection.

public List&lt;List&lt;Object&gt;&gt; getData(Collection&lt;T&gt; data) {
    try {
        Field[] fields = data.iterator().next().getClass().getDeclaredFields();
        Set&lt;String&gt; realFields = new LinkedHashSet&lt;String&gt;();
        for(Field field : fields) {
            if (!(java.lang.reflect.Modifier.isStatic(field.getModifiers()) ||
                  java.lang.reflect.Modifier.isFinal(field.getModifiers()))) {
                realFields.add(field.getName());
            }
        }
        List&lt;List&lt;Object&gt;&gt; realData = new ArrayList&lt;List&lt;Object&gt;&gt;();
        for(T element : data) {
            List&lt;Object&gt; row = new ArrayList&lt;Object&gt;();
            for(String realField : realFields) {
                Field currentField = element.getClass().getDeclaredField(realField);
                currentField.setAccessible(true);
                row.add(currentField.get(element));
            }
            realData.add(row);
        }
    } catch (Exception e) {
        //basic error handling, this will be improved;
        throw new RuntimeException(e);
    }
}
In principle, your code is correct (provided you really do not want to deal with fields in superclass). But it can be optimized: inside the first loop, you already have fields so there is no need to save their names in a collection and retrieve later - just use them in place.