反射通过方法赋值


public class BeanUtils {
//第一种:/// 使用到反射的地方
 //把request 的值 转换成对象并返回
    public static <T> T transBean(Class<T> clazz, HttpServletRequest request) {
        T entity = null;
        try {
            entity = clazz.newInstance();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            try {
                //使用属性描述器获得该属性的类型
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
                //得到了属性的类型.  为了转换  基本数据类型 和日期类型,等等非字符串类型
                Class aClassType = propertyDescriptor.getPropertyType();
                Method method = propertyDescriptor.getWriteMethod();

                if (aClassType.equals(Integer.class)) {//以此类推
                    method.invoke(entity, Integer.parseInt(value));
                }
                else {
                    method.invoke(entity, value);
                }

            }
            catch (Exception e) {
                e.printStackTrace();
            }

        }
        return entity;
    }

===========================================================================================

    //第二种 使用反射的地方

 //通过反射直接给对象赋值
    public static <T> void transBean(Object obj) {
            setVal(obj,"setCreateTime","创建时间");
            setVal(obj,"setCreateUser","创建人");
            setVal(obj,"setUpdateTime","修改时间");
            setVal(obj,"setUpdateUser","修改人");
    }

    public static void setVal(Object obj, String methodName, String val) {
        Class clazz = obj.getClass();
        Method method = null;
        try {
            method = clazz.getMethod(methodName, String.class);
            method.invoke(obj, val);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class User implements Serializable {
    private String name;
    private Integer age;
    private String createTime;
    private String createUser;
    private String updateTime;
    private String updateUser;
  //省略 get set 方法  ...,不在这里贴了
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值