To render Java 5 Enums as primitive strings, two steps are needed. First, Betwixt needs to be told that the Enum class should be treated as a primitive and not a Bean, otherwise the Enum will be introspected and the property accessor getDeclaringClass will be found. The result is this:

<myEnumType>
    <declaringClass>my.package.MyEnumType</declaringClass>
</myEnumType>

To make Betwixt treat Java 5 Enums as primitive types, implement a TypeBindingStrategy:

import org.apache.commons.betwixt.strategy.*;
/**
 * @author Jesse Sweetland
 */
public class EnumTypeBindingStrategy extends TypeBindingStrategy {
    public TypeBindingStrategy.BindingType bindingType(Class type) {
        TypeBindingStrategy.BindingType bindingType = null;
        if(Enum.class.isAssignableFrom(type)) {
            bindingType = TypeBindingStrategy.BindingType.PRIMITIVE;
        } else {
            bindingType = TypeBindingStrategy.DEFAULT.bindingType(type);
        }
        return bindingType;
    }
}

Once the TypeBindingStrategy class has been created, configure the Betwixt BeanWriter to use it:

StringWriter sw = new StringWriter();
BeanWriter bw = new BeanWriter(sw);
bw.getXMLIntrospector().getConfiguration().setTypeBindingStrategy(new EnumTypeBindingStrategy());

Next, we need to tell Betwixt how to convert back and forth between String and Enum values. To do this, implement an ObjectStringConverter:

import org.apache.commons.betwixt.expression.*;
import org.apache.commons.betwixt.strategy.*;
/**
 * @author Jesse Sweetland
 */
public class EnumObjectStringConverter extends DefaultObjectStringConverter {
    public String objectToString(Object object, Class type, Context context) {
        String value = null;
        if(object instanceof Enum) {
            value = ((Enum)object).name();
        } else {
            value = super.objectToString(object, type, context);
        }
        return value;
    }
    
    public Object stringToObject(String value, Class type, Context context) {
        Object object = null;
        if(Enum.class.isAssignableFrom(type)) {
            object = Enum.valueOf(type, value);
        } else {
            object = super.stringToObject(value, type, context);
        }
        return object;
    }
}

Now, configure the converter on the BeanWriter:

StringWriter sw = new StringWriter();
BeanWriter bw = new BeanWriter(sw);
bw.getXMLIntrospector().getConfiguration().setTypeBindingStrategy(new EnumTypeBindingStrategy());
bw.getBindingConfiguration().setObjectStringConverter(new EnumObjectStringConverter());

Now the above enumeration should render like this:

<myEnumType>SOME_CONSTANT</myEnumType>

Betwixt/TipsAndHints/Java5Enums (last edited 2009-09-20 23:48:41 by localhost)