// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Util {
    public static <T> Map<String,Object> toMap(T o) {
        try {
            Map<String,Object> res = new HashMap<String,Object>();
            for(PropertyDescriptor pd : Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors()) {
                Method getter = pd.getReadMethod();
                if(!getter.getReturnType().getName().startsWith("groovy.") && pd.getWriteMethod() != null) {
                    res.put(pd.getName(), getter.invoke(o));
                }
            }
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static <T> T fromMap(Map<String,Object> m, Class<T> clz) {
        try {
            T res = clz.newInstance();
            for(PropertyDescriptor pd : Introspector.getBeanInfo(clz).getPropertyDescriptors()) {
                Method setter = pd.getWriteMethod();
                Object o = m.get(pd.getName());
                if(o != null) {
                    setter.invoke(res, o);
                }
            }
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
