/**
* 封装数据,针对targetClass拥有所有orignClass的属性,且非内部类的情况
* @param orignInstance
* @param targetInstance
* @param orignClass
* @param targetClass
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void encapsulateData(Object orignInstance, Object targetInstance, Class orignClass, Class targetClass)
throws IllegalAccessException, InvocationTargetException {
Field[] fs = orignClass.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Method getMethod = ReflectUtil.getMethod(fs[i], orignClass);
Method setMethod = ReflectUtil.setMethod(fs[i], targetClass, fs[i].getType());
if (getMethod == null || setMethod == null) {
continue;
}
setMethod.invoke(targetInstance, getMethod.invoke(orignInstance));
}
}
反射获取set,get的工具类
反射:数据封装
最新推荐文章于 2024-02-22 19:49:58 发布
本文介绍了一种封装数据的方法,该方法允许将一个类的所有属性复制到另一个类中,前提是目标类不是内部类并且具备源类的所有属性。通过反射机制获取源类的所有字段,并找到对应的get和set方法来实现数据的复制。
619

被折叠的 条评论
为什么被折叠?



