posted 15 years ago
Just so we are clear on vocabulary and terminology, by 'attributes' in your statement update corresponding attributes, I assume you mean the Class's properties (a.k.a. instance variables)?
If I understand you correctly, you do not not necessarily want to update the master object's property with a new reference, but rather update that property's properties if they are different.
So if you started with this:
After updating you do not want to see this:
but rather want to see this:
such that original.aObj still points to instance A1 of AClass, but with updated properties. Is that correct?
If so, my questions would be:
1) How far down does it have to recurse? Just the one level? Or do you also only want to update the changed properties of say cObj and dObj? If you want to recurse, what will be the rule to stop its recursion?
2) Do want to do this for all types of properties for the Class (i.e. the Custom class)? Or just specific ones.
Here's what I had originally envisioned when I initially answered your post:
Since introspection can be expensive, and I suspect you will be calling this update method a lot, we can put in this simple optimization to only get the PropertyDescriptor array once for a class:
As a next step, we can break the method up into two parts:
That should allow you to put some logic in place to determine if you directly update the property via the updateProperty method, or if you recursively call the updateObject method on the property's object.
I would also improve the Exception handling so that the updateObject catches the various reflection exceptions and wraps them into a some type of application specific exception with a more meaningful message. And of course add Javadocs ;)
I'm by no means a reflection or introspection expert; so there may well be a better way of doing this type of thing.
Additionally, I'd ask about the overall architectural design. This seems to be getting complex rather fast. And potentially confusing. Is there possibly a different way to do these updates? Rather then getting a skeleton object with just the new values, is there not a way for what ever is supplying the new values to have the old values made available to it so it can supply a completely populated updated object and not one with just limited properties? Is there an alternative way to store this data rather than in the current objects that are being used? An in memory or embedded database (such as HSQLDB or Derby) perhaps. Databases lend themselves to the manipulation of data a little better than objects in some cases. Your solution might be the right one given the circumstances. But I always think its important to ask and ask again these types of questions throughout the design and development process.
[edit]Add new lines because text was too wide for screen. CR[/edit]