-1

I have a huge class with members, and i want to check on each member if its null. I don't want to add it manually, just run a for loop (or something similar) which will go over all the fields without 'human' addition every time a field is added.

So far, i can go over the fields, and receive the name of the fields (which is what i need). However, there's nothing on Field that checks if the value of it is null.

Here's what i have so far :

private class Test {
    String name1 = null;
    String name2 = "test";
    String name3 = null;
}

Test mainTest = new Test();
   for (Field field : mainTest.getClass().getDeclaredFields()) {
        if (field.isValueNull())
            Log.i("test", field.getName() + " is missing ");
   }

field.isValueNull() -> this is the method i'm looking for.

In this example, the print will be :

name1 is missing

name3 is missing

Dus
  • 4,052
  • 5
  • 30
  • 49
  • you can check this similar question : https://stackoverflow.com/questions/12362212/what-is-the-best-way-to-know-if-all-the-variables-in-a-class-are-null – Yash Nov 28 '17 at 15:30

1 Answers1

0

You can use the get() method of the Field object:

   Test mainTest = new Test();
   for (Field field : mainTest.getClass().getDeclaredFields()) {
        if (field.get(mainTest) == null)
            Log.i("test", field.getName() + " is missing ");
   }
Alejandro Goñi
  • 532
  • 1
  • 3
  • 14