-3

I have an object Card and has properties/fields name, id, date, number. How to find the number of non null fields. That is the number of fields that have been set. I do not have the list of functions or don't want to go down that road.

Eg:

  card.setName("abc");

I want the count to be 1 because only name is set.

user3310115
  • 1,372
  • 2
  • 18
  • 48
  • Why count non-null fields? What if only `date` is set? Then count is 1, but `name` is still not set. You should check all properties individually or use proper means to make sure that whatever limitations you have, they hold (e.g. appropriate constructors). – user1438038 Jan 09 '18 at 15:01
  • I just gave it as an example. Count can be 4 also with all the fields set. – user3310115 Jan 09 '18 at 15:46

1 Answers1

-1

Check the fields and increment counter if the field is not null:

public int countNotNullFields(Card card) {
    int counter = 0;
    if (card.getName() != null) {
        counter++;
    }
    ...
    return counter;
}
Georg Leber
  • 3,470
  • 5
  • 40
  • 63
  • 1
    Reflection is the only sane approach here. – Makoto Jan 09 '18 at 15:01
  • Sane?!... The op says he has an **object** with a defined count of fields. So for the described use case my code would work as requested. For sure, a more generic approach would be reflection, but that depends on the use case the op wants to implement. So why that downvote for correct code? – Georg Leber Jan 09 '18 at 15:16
  • I don't have the function list with me. So the previous solution wont work. Also I would need a more generic case. Its not just the name field that might be set. – user3310115 Jan 09 '18 at 15:44