java 反射遍历_java使用反射遍历类的字段

问题描述:

课程Course(字段非常多,一个一个修改不现实)修改

解决思路:

1.获得根据id,返回oldCourse

2.前端传过来的json字段String course,经过特殊处理,再使用GsonBuilder转化为curCourse

接着,使用反射遍历字段,将curCourse的其他字段值更新至oldCourse

//将不用特殊处理的course字段更新

private Course parseDetail(Course curCourse,Course oldCourse) {

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

for (Field field : fields) {

field.setAccessible(true);

try {

if(!field.getName().equals("serialVersionUID")&&field.get(curCourse)!=null) {

field.set(oldCourse,field.get(curCourse));

}

} catch (Exception e) {

e.printStackTrace();

}

field.setAccessible(false);

}

return oldCourse;

}

3.其他用法:可以使用反射触发set方法

传入类名和json字符串可使用反射进行任何共有的set方法进行赋值

/**

* 对某一条元数据进行修改

*

* @param entity 元数据实体名

* @param item 修改的条目

* @return boolean

* @date 18/08/08

*/

@SuppressWarnings({"unchecked"})

public boolean saveMetadataChange(String entity, String item) {

try {

Class c = this.entities.get(entity.substring(0, 1).toUpperCase() + entity.substring(1));

Object obj = gson.fromJson(item, c);

this.getClass().getMethod("add" + entity.substring(0, 1).toUpperCase() + entity.substring(1), c).invoke(this, obj);

return true;

} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return false;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值