mardi 12 mai 2020

Is there a smart way of finding all child of child and etc. and set a certain field in JAVA

Is there smart way looping through all childrens of a object with a certain extention and set a certain field in java. I considered reflection but seems dangerous.

Simply I want to call a set method on all objects of certain instance and which is null, and afterwards role back. Even that is it Parent->child->child

Example of Class structure:

abstract class AbstractFoo {
   Object obj;

   public void setObj(Object newValue) {
      this.obj = newValue;
   }
}
class FooParent extend AbstractFoo {
 FooChild1 fooChild;
 Set<FooChild2> fooChilds;
}

class FooChild1 extend AbstractFoo {

}

class FooChild2 extend AbstractFoo {
   FooChild3 fooChild
   Set<FooChild3> fooChilds
}

class FooChild3 extend AbstractFoo {

}

The purpose is that I want to set all by AbstractFoo.setObj to a default value and later on remove.

Some pseodo example:

Set<Boo> setMissingValueTemp(FooParent parent) {
   Set<Boo> boos = new ArrayList();
   // SomeKindOfAStream is flatten stream of all the object instance of AbstractFoo
   SomeKindOfAStream(parent).forEach { f ->
      if(f.getObj() == null) {
         Boo boo = new Boo()
         f.setObj(boo)
         boos.add(boo)
      }
   }
   return boos;
}

void removeTempValues(FooParent parent, Set<Boo> boos) {
   SomeKindOfAStream(parent).filter(c -> c instanceOf AbstractFoo).forEach { f ->
      if(boos.contains(f.getObj()))
         f.setObj(null)
   }
}




Aucun commentaire:

Enregistrer un commentaire