在java中HTML的目标属性值,Java反射机制调用对象的方法 —— 将一个对象的属性值赋值给另外一个对象的属性...

packagecom.wayne.common.utils;

​importcom.google.common.collect.Lists;importcom.wayne.common.exception.CopyPropertyException;

​importjava.lang.reflect.Field;importjava.lang.reflect.Method;importjava.util.List;

​/***@authorWayne

* @date 2019/6/5*/

public classBaseUtil {

​/*** 将一个集合中对象的值拷贝到另外一个对象,属性相同即赋值

*@paramsource 源数据,将此对象数据取出

*@paramtClass 目标对象,将取出的数据赋值到该对象中

*@param 源数据类型

*@param 目标数据类型

*@return被赋值后的目标对象集合

*@throwsCopyPropertyException 自定义异常,经过反射建立对象或调用方法时抛出的异常*/

public static List copyProperties(List source, Class tClass) throwsCopyPropertyException {

​//判断传入源数据是否为空,若是空,则抛自定义异常

if(null ==source) {throw new CopyPropertyException("数据源为空");

}

​//建立一个集合,用于存储目标对象,所有数据抓换完成后,将该集合返回

List targetList =Lists.newArrayList();

​//循环取到单个源对象

for(T t : source) {//获取源对象的类的详情信息

Class> sClass =t.getClass();//获取源对象的全部属性

Field[] sFields =sClass.getDeclaredFields();//获取目标对象的全部属性

Field[] tFields =tClass.getDeclaredFields();

E target;try{//经过类的详情信息,建立目标对象 这一步等同于UserTwo target = new UserTwo();

target =tClass.newInstance();

}catch(Exception e) {

e.printStackTrace();throw new CopyPropertyException("目标对象建立失败");

}

​//循环取到源对象的单个属性

for(Field sField : sFields) {//循环取到目标对象的单个属性

for(Field tField : tFields) {

​//判断源对象的属性名、属性类型是否和目标对象的属性名、属性类型一致

if(sField.getName().equals(tField.getName()) &&sField.getGenericType().equals(tField.getGenericType())) {

​try{//获取源对象的属性名,将属性名首字母大写,拼接如:getUsername、getId的字符串

String sName =sField.getName();char[] sChars =sName.toCharArray();

sChars[0] -= 32;

String sMethodName= "get" +String.valueOf(sChars);//得到属性的get方法

Method sMethod =sClass.getMethod(sMethodName);//调用get方法

Object sFieldValue =sMethod.invoke(t);

​//获取目标对象的属性名,将属性名首字母大写,拼接如:setUsername、setId的字符串

String tName =tField.getName();char[] tChars =tName.toCharArray();

tChars[0] -= 32;

String tMethodName= "set" +String.valueOf(tChars);//得到属性的set方法

Method tMethod =tClass.getMethod(tMethodName, tField.getType());//调用方法,并将源对象get方法返回值做为参数传入

tMethod.invoke(target, sFieldValue);

​break;

}catch(Exception e) {

e.printStackTrace();throw new CopyPropertyException("转换失败,请检查属性类型是否匹配");

}

}

}

}//将经过反射建立的目标对象放入集合中

targetList.add(target);

}//返回集合

returntargetList;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值