复制Java Bean属性
/** nowjava.com - 时代Java **/ //package com.nowjava; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { @SuppressWarnings("unchecked") public static void copyProperties(Object target, Object source) throws Exception { Class sourceClz = source.getClass(); Class targetClz = target.getClass(); /**来 自 n o w j a v a . c o m - 时 代 Java**/ Field[] fields = sourceClz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { String fieldName = fields[i].getName(); Field targetField = null; try { // targetClz?fieldName? targetField = targetClz.getDeclaredField(fieldName); } catch (SecurityException e) { e.printStackTrace(); break; } catch (NoSuchFieldException e) { continue; } // sourceClz?targetClz if (fields[i].getType() == targetField.getType()) { // ?get?set? String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); // get?set?Method Method getMethod; try { getMethod = sourceClz.getDeclaredMethod(getMethodName, new Class[] {}); Method setMethod = targetClz.getDeclaredMethod( setMethodName, fields[i].getType()); // source?getMethod Object result = getMethod.invoke(source, new Object[] {}); // target?setMethod if (result != null) { if (!((result instanceof String) && "" .equals(result.toString())) && !((result instanceof Integer) && (Integer) result <= 0) && !((result instanceof Long) && (Long) result <= 0)) { setMethod.invoke(target, result); } } } catch (SecurityException e) { e.printStackTrace(); } catch (