OGNL TableModel instead of BeanPropertyTableModel

Code Poet writes about a BeanPropertyTableModel which is an adater to use a list of object as a javax.swing.table.TableModel by acessing the properties with commons-beanutils.

I suppose to go further an use OGNL for a more powerful expression language. I only outline the implementation here:

class OGNLTableModel() {
  private List items;
  private Object[] compliedExpression;

 public OGNLTableModel(List items, String[] columnExpressions) {
        ognlExprs = new Object[columnExprs.length];
        for (int i = 0; i < columnExprs.length; i++) {
            try {
            String columnExpr = columnExprs[i];
                ognlExprs[i] = Ognl.parseExpression(columnExpr);
            } catch (ExpressionSyntaxException e) {
                throw new IllegalArgumentException(
                   "Error for property »" + columnExprs[i] 
                     + "« : »" + e + "«");
            } catch (OgnlException e) {
                throw new IllegalArgumentException(
                   "Error for property »" + columnExprs[i] 
                     + "« : »" + e + "«");
            }
        }
    }
    public Object getValueAt(int rowIndex, int columnIndex) {
        try {
            return Ognl.getValue(ognlExprs[columnIndex],
                items.get(rowIndex);
        } catch (OgnlException e) {
            return "Error for property »"
             + columnExprs[columnIndex] + "« : »" + e + "«";
        }
    }
}

The actual implementation I use can handle column names, I left to out to make the idea clear. Use it like this:

// example
List list = orderService.findAllCustomers();
TableModel tm = new OGNLTableModel(list,
     new String[]{"id", "firstname", "lastname", "orders.size",
                             "orders[orders.size].date});
address
terms

{ Comments are closed! }

blog
Bear