java 反射实现深拷贝_Java 反射拷贝相同的属性值到指定对象中(两种实现方式)...

范例:

public class ReflectUtils {

private ReflectUtils() {};

/**

* 对象反射赋值

*

* @param source 目标对象

* @param target 赋值对象

*/

public static void copyBeanFieldsValue(Object source, Object target) {

Field[] fields = target.getClass().getDeclaredFields();

if (fields != null && fields.length > 0) {

for (int x = 0; x < fields.length; x++) {

Object value = BeanUtil.getFieldValue(source, fields[x].getName());

try {

Method setterMethod = target.getClass()

.getDeclaredMethod("set" + StringUtils.capitalfor(fields[x].getName()), fields[x].getType());

value = TypeUtils.castToJavaBean(value, fields[x].getType());

setterMethod.invoke(target, value);

} catch (Exception e) {

}

}

}

}

/**

* 通过存储器赋值

*

* @param source 目标对象

* @param target 赋值对象

*/

public static void copyProperties(Object source, Object target) {

PropertyDescriptor[] propertyDescriptors = BeanUtil.getPropertyDescriptors(target.getClass());

if (propertyDescriptors != null && propertyDescriptors.length > 0) {

for (int x = 0; x < propertyDescriptors.length; x++) {

Object fieldvalue = BeanUtil.getFieldValue(source, propertyDescriptors[x].getName());

try {

Object castValue = TypeUtils.castToJavaBean(fieldvalue, propertyDescriptors[x].getPropertyType());

propertyDescriptors[x].getWriteMethod().invoke(target, castValue);

} catch (Exception e) {

}

}

}

}

}

public class StringUtils {

private StringUtils() {};

/**

* 首字母大写替换

*

* @param name 指定替换字符串

* @return 范例:

*/

public static String capital(String name) {

if (StrUtil.isBlank(name)) {

return name;

}

if (name.length() == 1) {

name = name.toUpperCase();

} else {

name = name.substring(0, 1).toUpperCase() + name.substring(1);

}

return name;

}

/**

* 首字母大写

*

* @param name 指定替换字符串

* @return 范例:

*/

public static String capitalFor(String name) {

if (StrUtil.isBlank(name)) {

return name;

}

if (name.length() == 1) {

name = name.toUpperCase();

} else {

String str = name.substring(0, 2);

if (Character.isLowerCase(str.charAt(0))) { // 第一个是否为小写

if (Character.isUpperCase(str.charAt(1))) { // 第二个是否为大写

return name;

} else {

name = name.substring(0, 1).toUpperCase() + name.substring(1);

}

}

}

return name;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值