Chapter 6. Type Conversion

When performing set operations on properties or calling methods it is often the case that the values you want to set have a different type from the expected type of the class. OGNL supports a context variable (set by OgnlRuntime.setTypeConverter(Map context, TypeConverter typeConverter)) that will allow types to be converted from one to another. The default type converter that is uses is the ognl.DefaultTypeConverter, which will convert among numeric types (Integer, Long, Short, Double, Float, BigInteger, BigDecimal, and their primitive equivalents), string types (String, Character) and Boolean. Should you need specialized type conversion (one popular example is in Servlets where you have a String[] from an HttpServletRequest.getParameters() and you want to set values with it in other objects; a custom type converter can be written (most likely subclassing ognl.DefaultTypeConverter) to convert String[] to whatever is necessary.

public interface TypeConverter
{
    public Object convertValue(Map context,
                                Object target,
                                Member member,
                                String propertyName,
                                Object value,
                                Class toType);
}

Note that ognl.DefaultTypeConverter is much easier to subclass; it implements TypeConverter and calls it's own convertValue(Map context, Object value, Class toType) method and already provides the numeric conversions. For example, the above converter (i.e. converting String[] to int[] for a list of identifier parameters in a request) implemented as a subclass of ognl.DefaultTypeConverter:

HttpServletRequest request;
Map context = Ognl.createDefaultContext(this);

/* Create an anonymous inner class to handle special conversion */
Ognl.setTypeConverter(context, new ognl.DefaultTypeConverter() {
    public Object convertValue(Map context, Object value, Class toType)
    {
        Object  result = null;

        if ((toType == int[].class) && (value instanceof String[].class)) {
            String  sa = (String[])value;
            int[]   ia = new int[sa.length];

            for (int i = 0; i < sa.length; i++) {
                Integer     cv;

                cv = (Integer)super.convertValue(context,
                                                    sa[i],
                                                    Integer.class);
                ia[i] = cv.intValue();
            }
            result = ia;
        } else {
            result = super.convertValue(context, value, toType);
        }
        return result;
    }
});
/* Setting values within this OGNL context will use the above-defined TypeConverter */
Ognl.setValue("identifiers",
                context,
                this,
                request.getParameterValues("identifier"));