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

public class AutoMap<TFROM,TTO> {
    public static class MethodPair {
        private Method getter;
        private Method setter;
        private boolean trim;
        public MethodPair(Method getter, Method setter, boolean trim) {
            this.getter = getter;
            this.setter = setter;
            this.trim = trim;
        }
        public Method getGetter() {
            return getter;
        }
        public Method getSetter() {
            return setter;
        }
        public boolean getTrim() {
            return trim;
        }
    }
    private List<MethodPair> conv;
    public AutoMap(Class<TFROM> from, Class<TTO> to) throws IntrospectionException {
        this(from, to, false);
    }
    public AutoMap(Class<TFROM> from, Class<TTO> to, boolean trim) throws IntrospectionException {
        conv = new ArrayList<MethodPair>();
        for(PropertyDescriptor pdfrom : Introspector.getBeanInfo(from).getPropertyDescriptors()) {
            for(PropertyDescriptor pdto : Introspector.getBeanInfo(to).getPropertyDescriptors()) {
                if(pdfrom.getName().equals(pdto.getName())) {
                    Method getter = pdfrom.getReadMethod();
                    Method setter = pdto.getWriteMethod();
                    if(getter != null && setter != null) {
                        conv.add(new MethodPair(getter, setter, trim && pdfrom.getPropertyType().equals(String.class)));
                    }
                }
            }
        }
    }
    public void convert(TFROM from, TTO to) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        for(MethodPair mp : conv) {
            if(mp.getTrim()) {
                mp.getSetter().invoke(to, ((String)mp.getGetter().invoke(from)).trim());
            } else {
                mp.getSetter().invoke(to, mp.getGetter().invoke(from));
            }
        }
    }
}
