失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 将一个类中的字段赋值到另一个类同名同类型字段

将一个类中的字段赋值到另一个类同名同类型字段

时间:2021-03-14 15:13:36

相关推荐

将一个类中的字段赋值到另一个类同名同类型字段

//将对象中同名属性赋值到另外一个对象的同名属性public static void copy(Object source, Object target) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InvocationTargetException {Class sourceClass = source.getClass();//得到对象的ClassClass targetClass = target.getClass();//得到对象的ClassField[] 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方法}}}}

如果觉得《将一个类中的字段赋值到另一个类同名同类型字段》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。