集册 Java实例教程 通过getter和setter方法复制对象

通过getter和setter方法复制对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

510
通过getter和setter方法复制对象


import java.lang.reflect.Method;
/**
 * NowJava.com - 时代Java 提 供 
**/

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 = "nowjava.com";

        Object dest = "nowjava.com";
        /*
        来 自*
         时 代 J a v a 公 众 号
        */

        copy(src,dest);

    }

    

    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 met
展开阅读全文