I currently have code that automatically applies parameter values from a hash map to a model by reflectively looking up the appropriate setter methods.
I mentioned that I’d rewrite this to use the reflection API to directly set fields. In fact, it would be better to fully implement the Key-Value Coding hierarchy of Cocoa: first look for a setter method, and then directly set the field.
Directly setting the field, of course, breaks data hiding. This feature is meant for debuggers, not for applications. So, rather than just letting the standard parameter-setting capabilities set any field, there will be an annotation, @Parameter, to specify that a field should be accessible as a parameter to be set during a model’s MyModel(Map<String, Object> parameters) constructor.
There will be no setParameter method for use at runtime, because the only time parameters should be set is during object creation. Any class can choose to bypass this restriction by providing setter methods or declaring a parameter public, but
What about reading parameters at runtime? Just use the standard methods. A model will be able to access its own fields as usual. If the model wants other objects (such as its children) to have access, it should declare an accessor method.
I was hoping it would be possible to modify final fields using reflection in the constructor, but this is not the case (at least not with JDK 5.0—apparently it was possible in 1.3.0). That would let you do things like declaring parameters with @Parameter public final int beta = 0.3;, where the default value of a parameter is set in its declaration, AND it’s publicly accessible (for speed and convenience) without being modifiable, AND it gets automatically set in the constructor. I guess I can live with @Parameter public int beta = 0.3; (dangerous) or @Parameter private int beta = 0.3; + an accessor (safe).
In short, parameters will work like this:
- Parameter fields are declared with the
@Parameterannotation. - By calling the
Modelparameter-setting constructor in a subclass constructor, all parameters present in the parameter map will get set automatically. - Normal access modifiers will apply at runtime.