How do I safely call setter after getter chain eg foo.getX().getY().setZ(...);
? For example, suppose I have a nested POJO, and I want to be able to set a field of a nested object.
Foo foo = ...
foo.getX().getY().setZ(...);
I want the behavior to be such that if X and Y do not exist then they are created automatically; otherwise it reuses the existing object.
In other words, I want it to be behave equivalent to
Foo foo = ...
X x = foo.getX();
if (x == null) {
x = new X();
foo.setX(x);
}
Y y = x.getY();
if (y == null) {
y = newY();
x.setY(y);
}
y.setZ(...);
I'm wondering if there is a trick out there using reflection/functional that comes close to this.
I also have the following constraints:
- I cannot modify any of the classes
- The solution must know about only the public getters and setters, not the private instance variables
- I want the getter to modify the internal state only when specifically requested; I don't want
x = foo.getX()
to modify foo.
Aucun commentaire:
Enregistrer un commentaire