Search code examples
javaloopsobjectmember

How to iterate through an object when it is not an array type


My object LabOrder contains data that cannot locate with array index. What I want to do is print the non-null values in the object like name = John. How can I iterate through that non null values and print?


Solution

  • You could use reflection to iterate over the object's fields:

    Field[] fields = obj1.getClass().getDeclaredFields();
    
    for (Field field : fields) {
        field.setAccessible(true);
        String name = field.getName();
        Object value = field.get(obj1);
        if (value != null) {
            System.out.println(name + " = " + value);
        }
    }