Home > Java > Converting Entity Objects to SelectItem Objects using reflection

Converting Entity Objects to SelectItem Objects using reflection

This method is very useful for development JSP using JSF. This method converts a list of Entity Objects or any class that contains the items for a JSF ListBox to SelectItem Object. The class must have at least two methods:

  1. The id method that return de id of the Item
  2. The description method that return the description of the Item
public List<SelectItem> entityToSelectItem(List _items, String _idMethod, String _descMethod)throws Exception {
  List<SelectItem> items = new ArrayList<SelectItem>();

  Method idMethod = null;
  Method descMethod = null;

  for (int i = 0; i < _items.size(); i++) {
    Object item = _items.get(i);
    // On the first run, initialize reflection methods for object
    if (idMethod == null) {
      Class obj = item.getClass();
      idMethod = obj.getMethod(_idMethod, new Class[]{});
      descMethod = obj.getMethod(_descMethod, new Class[]{});
    }
    // invoke Methods
    String id = (String) idMethod.invoke(item, new Object[]{});
    String name = (String) descMethod.invoke(item, new Object[]{});

    SelectItem selectItem = new SelectItem();
    selectItem.setLabel(name);
    selectItem.setValue(id.toString());
    items.add(selectItem);
  }
  return items;
}
Categories: Java
  1. August 2, 2009 at 5:47 pm

    Great idea, but will this work over the long run?

  1. No trackbacks yet.

Leave a comment