copy object via getter and setter method - Java Reflection

Java examples for Reflection:Getter

Description

copy object via getter and setter method

Demo Code


import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

public class Main{
    public static void main(String[] argv) throws Exception{
        Object src = "java2s.com";
        Object dest = "java2s.com";
        copy(src,dest);/*from w ww . ja  v  a2s.com*/
    }
    
    private static final Set<Class> ALLOW_TYPES;
    
    public static final int SET_START = "set".length();
    
    public static final int IS_START = "is".length();
    
    public static void copy(Object src, Object dest) {
        Class srcClass = src.getClass();
        Class destClass = dest.getClass();

        for (Method method : srcClass.getMethods()) {
            Class returnType = method.getReturnType();

            if (!ALLOW_TYPES.contains(returnType)) {
                continue;
            }

            if (isGetter(method)) {
                try {
                    Object result = method.invoke(src);

                    if (result == null) {
                        continue;
                    }

                    String methodName = getter2Setter(method.getName());
                    Method setter = destClass.getMethod(methodName,
                            returnType);
                    setter.invoke(dest, result);
                } catch (NoSuchMethodException ex) {
                    // ignore
                    continue;
                } catch (Throwable ex) {
                    System.err.println(ex);
                }
            }
        }
    }
    
    public static boolean isGetter(Method method) {
        String name = method.getName();
        boolean hasNoParam = method.getParameterTypes().length == 0;
        boolean startsWithGet = (name.length() > SET_START)
                && name.startsWith("get");
        boolean startsWithIs = (name.length() > IS_START)
                && name.startsWith("is");

        return hasNoParam && (startsWithGet || startsWithIs);
    }
    
    public static String getter2Setter(String methodName) {
        if (methodName.startsWith("get")) {
            return "s" + methodName.substring(1);
        } else if (methodName.startsWith("is")) {
            return "set" + methodName.substring(2);
        } else {
            throw new IllegalArgumentException(
                    "method not start with get or is.");
        }
    }
}

Related Tutorials