1 取得Class对象:
Class parentClass=Class.forName(classType);
切记:classType必须是类的完整名,包括包名和类名.
2.取得Method对象:
Method m = parentClass.getMethod(method,new Class[]{String.class} );
3.使用Method 对象
m.invoke(destPersist,new Object[]{"feixiang" });
解释:调用的是destPersist 对象的方法
5.用反射实现Bean拷贝
/**
* Only available for the beans whoes structure are identified
*
* @param to
* @param from
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void copyBeanProperties(Object to, Object from)
throws SecurityException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Class fromClass = from.getClass();
Class toClass = to.getClass();
Field[] fields = fromClass.getDeclaredFields();
for (int i=0; i<fields.length; i++) {
String fieldName = firstCharToUpperCase(fields[i].getName());
Method fromMethod = null;
Method toMethod = null;
try {
try {
fromMethod = fromClass.getDeclaredMethod(
"get" + fieldName, null);
} catch (NoSuchMethodException e) {
if (Boolean.class.getName().toUpperCase().endsWith(
fields[i].getType().getName().toUpperCase())) {
fromMethod = fromClass.getDeclaredMethod(
"is" + fieldName, null);
} else {
continue;
}
}
try {
toMethod = toClass.getDeclaredMethod(
"set" + fieldName,
new Class[] {fields[i].getType()});
} catch (NoSuchMethodException e) {
if (Boolean.class.getName().toUpperCase().endsWith(
fields[i].getType().getName().toUpperCase())) {
toMethod = fromClass.getDeclaredMethod(
"is" + fieldName, null);
} else {
continue;
}
}
} catch (NoSuchMethodException e) {
continue;
}
toMethod.invoke(to, new Object[] {fromMethod.invoke(from, null)});
}
}