How do I iterate over class members?

Yes, you do need reflection. It would go something like this:

public static void getObject(Object obj) {
    for (Field field : obj.getClass().getDeclaredFields()) {
        //field.setAccessible(true); // if you want to modify private fields
                 + " - " + field.getType()
                 + " - " + field.get(obj));

(As pointed out by ceving, the method should now be declared as void since it does not return anything, and as static since it does not use any instance variables or methods.)

See the reflection tutorial for more.

Leave a Comment