Segue minha mais nova implementação. Não sei se será útil pra você... pra mim é. Falta dar uma melhorada nisso aí, terminei era umas duas da manhã, não estava mais enxergando nada... =)
Mas acho que já quebra um galho...
Bem, trata-se de um conversor de Collection (java.util.Collection), no caso fiz pensando especificamente no List, mas enfim... serve para outras implementações também. Aliás, por isso a classe abstrata...
Para quem não conhece o SimpleListData, trata-se de um objeto do framework web mentawai , utilizado, por exemplo, para popular selectboxes, pois, esta implementação se caracteriza por possuir chave/ valor.
Segue aí pra quem quiser aproveitar, e até dar aquela melhorada. A idéia de utilizaçao é mais ou menos assim:
objListToSimpleListDataConverter.convert(CategoriaService.listarTodasCategorias(), "id", "nome"));
Ou seja, informa-se ao método convert como parâmetros, a Collection (List, HashSet, etc), o nome do campo que será utilizado como chave e o nome do campo que será utilizado como valor, ambos campos do objeto que está na lista, claro!). Aceita-se listas de qualquer tipo de objeto, pois esta implementação se utiliza da API Reflection do Java, que nos proporciona a chance de criar muitas utilidades genéricas, como esta.
Bom proveito!
A classe-pai:
import java.util.Collection;
import org.mentawai.list.SimpleListData;
public abstract class SimpleListDataConverter {
public abstract SimpleListData convert(Collection<Object> objList, String strKeyGetter, String strValueGetter);
}
A interface:
import java.util.Collection;
import org.mentawai.list.SimpleListData;
public interface IListToSimpleListDataConverter {
/**
* Converts a List<Object> collection into a SimpleListData object.
* @param objList - List object to be converted into a key/value SimpleListData object.
* @param strKeyField - Name of the field which will represent the key object of a SimpleListData element.
* @param strValueField - Name of the field which will represent the value object of a SimpleListData element.
* @return SimpleListData
*/
public abstract SimpleListData convert(Collection<Object> objList, String strKeyField, String strValueField);
}
A implementação:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import org.mentawai.list.SimpleListData;
/**
* @author Saulo Junior
*/
public class ListToSimpleListDataConverter extends SimpleListDataConverter implements IListToSimpleListDataConverter {
private Method keyMethod = null;
private Method valueMethod = null;
private String key = null;
private String value = null;
/**
* Converts a List<Object> collection into a SimpleListData object.
* @param objList - List object to be converted into a key/value SimpleListData object.
* @param strKeyField - Name of the field which will represent the key object of a SimpleListData element.
* @param strValueField - Name of the field which will represent the value object of a SimpleListData element.
* @return SimpleListData
*/
public SimpleListData convert(Collection<Object> objList, String strKeyField, String strValueField){
SimpleListData objSimpleListData = new SimpleListData();
for (Iterator<Object> iterator = (Iterator<Object>) objList.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
try {
keyMethod = object.getClass().getDeclaredMethod("get" +
strKeyField.replace(String.valueOf(strKeyField.charAt(0)),
String.valueOf(strKeyField.charAt(0)).toUpperCase()));
valueMethod = object.getClass().getDeclaredMethod("get" +
strValueField.replace(String.valueOf(strValueField.charAt(0)),
String.valueOf(strValueField.charAt(0)).toUpperCase()));
key = String.valueOf(keyMethod.invoke(object));
value = String.valueOf(valueMethod.invoke(object));
objSimpleListData.add(key,value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
System.out.println("One of the fields does not exist for the type " +
object.getClass().getName());
}
}
return objSimpleListData;
}
}