I have a class representing computer parts (specifically RAM modules) with properties in it, such as name, brand, price, and capacity. It needs to have a method to insert its own data into a database. I want it to insert all of its properties into the database, unless that property is null. Would the best way to do this to loop through a Map containing the String title of the column of the database and the method to obtain the corresponding property of the object? This is my first time using reflection, so if this is in fact the best way to do this, a snippet of sample code would be appreciated.
Thanks in advance,
Ben
No. You are really talking more about a serialization problem than persistence. Persistence maintains the notion of entities, that have predefined properties, that are mapped to columns in the db. If you are just going to discover the properties, then you are basically serializing the object.
The problem with doing that with reflection is that it will get really complicated when you start having graphs of objects that could contain cycles (objects that point back to nodes that have already been encountered).
The other option is to just have a simple property mapping protocol, like Cocoa does: each object type knows how to encode itself, then decode itself, but from an encoder or decoder, which is format independent. So if you do it now in XML for 50 different entities then later want to support JSON you can without changing any of the entity code.