Monday, April 7, 2008

Generic ValueLists and their defaults

I came across a typical problem yesterday: I have some domain objects modeled for hibernate/jpa. Above that I have a service layer. The domain objects shouldnt have access to the service layer. Now guess I have a generic model for ValueLists and Values. Everywhere in the model where I need a valueList I simply reference a generic Value. Now the model doesnt know wich ValueList ist references. Now I set the default values on each newly created entity with some generic code:
So each ValueList has a default Value which I want to be set in the UI o for e.g. on a combo. One way would be to make the different ValueLists different types ( I saw that before) but that means generating a new Type for every new ValueList. So I came to a different solution. I annotate each entity-to-value relation with the name of the corresponding ValueList as you can see. On each new entity I set the default values with some simple generic reflection code as you can see below.

for (Method m : o.getClass().getMethods()) {
Annotation a = m.getAnnotation(ValueListName.class);
if (a != null) {
ValueListName valuelistname = (ValueListName) a;
ValueList list = service.getValueList(;
Value defaultValue = list.getDefaultValue();
if (defaultValue != null) {
String getterName = m.getName();
String setterName = "s" + getterName.substring(1);

Method setter = o.getClass().getMethod(setterName,Value.class);
setter.invoke(o, defaultValue);