mercredi 7 octobre 2020

Get all non null fields from Nested Objects - Java

I am looking to collect every non null field in an Object that looks as so:

Class ObjectA{
    Set<ObjectB> objectBSet = new hashmap<>
}

Class ObjectB{
   private String id
   private Set<InnerBObject>  innerBObjectSet =new hashmap<>{

}

class InnerBObject{ 
   private String age;
   private String name

} 

I want to traverse ObjectA and all it's children and collect any non null fields. I want to add to a Map<String,String>, I know I can loop through each object and do a null check on each field, an example would be:

if(ObjectA.getObjectBSet != null){
   loop objectBSet
     if(objectBSet.get(i).getId !=null)map.put("objectB","id")
     if(objectBSet.get(i).getBo !=null) 
        loop innerBObjectSet 
          if(innerBObjectSet .get(i).getName !=null)map.put("InnerBObject", "name")

}

This approach doesn't work well at scale when multiple objects are nested. The end goal is to get the Class in which the field are null and store them in a Map. So Map<ClassName, fieldName)





Aucun commentaire:

Enregistrer un commentaire