È possibile utilizzare Commons BeanUtilsBeanMap
per questo.
Map map = new BeanMap(someBean);
Aggiornamento: dal momento che non è un'opzione a causa di alcuni problemi di biblioteca dipendenza apparenti in Android, ecco un esempio di base kickoff come si potrebbe fare con piccolo aiuto di Reflection API:
public static Map<String, Object> mapProperties(Object bean) throws Exception {
Map<String, Object> properties = new HashMap<>();
for (Method method : bean.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& method.getName().matches("^(get|is).+")
) {
String name = method.getName().replaceAll("^(get|is)", "");
name = Character.toLowerCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "");
Object value = method.invoke(bean);
properties.put(name, value);
}
}
return properties;
}
Se java.beans
API fosse disponibile, allora si può solo fare:
public static Map<String, Object> mapProperties(Object bean) throws Exception {
Map<String, Object> properties = new HashMap<>();
for (PropertyDescriptor property : Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors()) {
String name = property.getName();
Object value = property.getReadMethod().invoke(bean);
properties.put(name, value);
}
return properties;
}
Santo schifo! Sembra super utile! Sai qualcosa delle sue implicazioni in termini di prestazioni? –
Reflection ha sempre un costo in termini di prestazioni. Niente da fare contro. Ma puoi fidarti che i ragazzi di BeanUtils l'hanno ottimizzato il più possibile. È una libreria molto popolare. – BalusC
Freddo. Devo implementare qualsiasi tipo di interfaccia sui miei POJO, o sto usando get * naming abbastanza (sto usando POI immutabili con costruttori privati istanziati usando un Builder)? –