Navigating a Dynamically Enhanced Copy of an Object Tree
StringTemplate provides a very nice source code generation mechanism, but it is a little restrictive in obtaining data from the data passed to the template. We ran into this when we wanted to use StringTemplate to generate source code from a Modello model:
The
ModelloFieldcarries some metadata, but you won't be able to access this data without invoking an operation onModelFieldthat does meet the bean getter naming convention. The operation to invoke isModelField.getMetadata(Class clazz). Since StringTemplate is restricted to access only data exposed through bean-alike accessors, you will never be able to call this operation directly from StringTemplate.-
We needed to generate Java Bean accessors from a
ModelField. TheModelFieldhas a property name that we could access, so it seemed to be not that hard. But then we realized that we had to change theModelField's name to start with a capital in order to meet the cammel case getter and setter patterns: so in case of aModelloFieldwith name"foo", we needed to generate "Foo" when generating the setter ("setFoo(String foo)") and getter ("String getFoo()").As in the previous example, there is no easy way out: there are no bean-alike operations on
java.lang.Stringthat allow you to return a version of the String with the first character turned into a capitcal. (So there's no operation likeString getSameStringStartingWithUpperCase()defined onjava.lang.String.)
Terence Parr has suggested to use connector or "glue" objects in these cases. However, if you want to navigate through a network of objects in your template, then it can be quite challenging to insert these glue objects. And that is exactly our problem: we don't want to replace the entire Modello model by another copy, simply because we need an extra couple of accessors. In the Modello case, we were able to replace the ModelField by a manually constructed Proxy called EnhancedModelField. However, this was a painfull excercise, and now we are starting to see the need for enhanced ModelClass and Model classes as well.
With all of this in mind, we are starting to think about using CGLIB to construct an enhanced replica of the Modello model on the fly. An alternative would be to change StringTemplate to provide support for dynamically inserting "glue" objects. The result would be similar to StringTemplate's support for AtttributeRenderers: you would simply register a Connector class for the types that need to be enhanced, and StringTemplate would wrap the original type with the Connector instance whenever it encounters an instance of the original type.
Let's wait and see how Terence feels about that.
Java StringTemplate ( Oct 06 2005, 07:18:01 AM CEST ) Permalink Comments [0]

