代码有好多高级代码,现在给大家看一个,就是复制相同属性的值到另一个类。
例如:A类中有String name,int score;B类中有String name ,int score,String schoole,现在想把A类中的name和score的值复制到B中,就可以使用下面的方法,我感觉代码写的不错,我们都学习一下:
public static void copy(Object source, Object target) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InvocationTargetException {
Class sourceClass = source.getClass();//得到对象的Class
Class targetClass = target.getClass();//得到对象的Class
Field[] sourceFields = sourceClass.getDeclaredFields();//得到Class对象的所有属性
Field[] targetFields = targetClass.getDeclaredFields();//得到Class对象的所有属性
for(Field sourceField : sourceFields){
String name = sourceField.getName();//属性名
Class type = sourceField.getType();//属性类型
String methodName = name.substring(0, 1).toUpperCase() + name.substring(1);
Method getMethod = sourceClass.getMethod("get" + methodName);//得到属性对应get方法
Object value = getMethod.invoke(source);//执行源对象的get方法得到属性值
for(Field targetField : targetFields){
String targetName = targetField.getName();//目标对象的属性名
if(targetName.equals(name)){
Method setMethod = targetClass.getMethod("set" + methodName, type);//属性对应的set方法
setMethod.invoke(target, value);//执行目标对象的set方法
}
}
}
}