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:
- The id method that return de id of the Item
- 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
Great idea, but will this work over the long run?