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?
Asked
Active
Viewed 973 times
1

Mohammed Javad
- 629
- 8
- 18
-
1Do you want to iterate over all attributes? Can you edit the class? – jhamon Dec 06 '18 at 17:11
-
Overwrite `toString` method of that object, if you have access to the code. – Dec 06 '18 at 17:16
-
you can use reflexion for that, see https://stackoverflow.com/questions/20899045/how-to-get-all-attributes-of-a-class – Alice Oualouest Dec 06 '18 at 17:17
-
1Yes i want to iterate through all attributes. In that object one attribute called name will be there. So what i exactly want to do is pass that name in to decrypt method. Because it is in the encrypted format. – Mohammed Javad Dec 06 '18 at 17:17
3 Answers
2
You should use reflection. This will help you:
ClassABC abc = new ClassABC();
for (Field field : abc.getClass().getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
Object value = field.get(abc);
System.out.printf("%s: %s%n", name, value);
}

Mohsen
- 4,536
- 2
- 27
- 49
2
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);
}
}

Mureinik
- 297,002
- 52
- 306
- 350
1
Try below:
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
LabOrder order = new LabOrder();// Instantiation of the bean.
LabOrder order = Introspector.getBeanInfo(LabOrder.class);
for (PropertyDescriptor propertyDesc : order.getPropertyDescriptors()) {
String propertyName = propertyDesc.getName();
Object value = propertyDesc.getReadMethod().invoke(order);
System.out.println(propertyName);
System.out.println(value);
}

Aditya Narayan Dixit
- 2,105
- 11
- 23