Java tutorial
/* * Copyright (C) 2014 BIGITLIliyuanguo <BIGITLI@foxmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.beanutils.BeanUtils; /** * ?? * * @author: liyuanguo * @mailto: BIGITLI@foxmail.com * @date: 2014108 * @blog : http://BIGITLI.github.io/ */ public class TestCopy { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { //?? User user = new User(6, ""); //?? UserCopy copy = new UserCopy(); //???????? //copy1(user,copy); //copy2(user,copy); BeanUtils.copyProperties(copy, user); System.out.println(user); System.out.println(copy); } private static void copy2(Object src, Object dest) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class srcClass = src.getClass(); Class destClass = dest.getClass(); Method[] srcMs = srcClass.getDeclaredMethods(); for (Method srcM : srcMs) { //?? String methodName = srcM.getName(); if (methodName.startsWith("get")) { //srcsrcM? Object value = srcM.invoke(src, new Object[] {}); //methodName.substring(3)?? String destSetName = "set" + methodName.substring(3); try { //destClass?getMethod ?? ??? //? ?????value? Method destMethod = destClass.getMethod(destSetName, new Class[] { value.getClass() }); //?? dest value? destMethod.invoke(dest, new Object[] { value }); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } } } //n?n?? private static void copy1(User user, UserCopy copy) { // copy.setId(user.getId()); copy.setName(user.getName()); } }