反射增加与更新

package com.system.ds.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import com.system.ds.model.DSBom;

public class DTOBuilder {
	/**
	 * 方法入口,得到Dto
	 * 
	 * @param request
	 * @param dtoClass
	 *            传入的实体类
	 * @return
	 */
	public static Object getDTO(HttpServletRequest request, Class<?> dtoClass) {
		Object dtoObj = null;
		if ((dtoClass == null) || (request == null))
			return dtoObj;
		try {
			// 实例化对象
			dtoObj = dtoClass.newInstance();
			setDTOValue(request, dtoObj);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return dtoObj;
	}

	/**
	 * 方法入口,更新Dto
	 * @throws Exception 
	 */
	public static void updateDTO(HttpServletRequest request, Object obj) throws Exception{
		setDTOValue(request, obj);
	}
	
	
	/**
	 * 保存数据
	 * 
	 * @param request
	 * @param dto
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws Exception
	 */
	private static void setDTOValue(HttpServletRequest request, Object dto) throws Exception{
		if ((dto == null) || (request == null))
			return;
		// 得到类中所有的方法 基本上都是set和get方法
		Method[] methods = dto.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			// 方法名
			String methodName = methods[i].getName();
			// 方法参数的类型
			Class<?>[] type = methods[i].getParameterTypes();
			// 当时set方法时,判断依据:setXxxx类型
			if ((methodName.length() > 3) && (methodName.startsWith("set")) && (type.length == 1)) {
				// 将set后面的大写字母转成小写并截取出来
				String name = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
				Object objValue = getBindValue(request, name, type[0]);
				//Boolean flag = name.endsWith("_id");//设置_id及xxx_id的属性不在此外自动设置,在编写程序时,手动设置.
				if (objValue != null) {
					Object[] value = { objValue };
					invokeMothod(dto, methodName, type, value);
				}
			}
		}
	}

	/**
	 * 通过request得到相应的值
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param bindName
	 *            属性名
	 * @param bindType
	 *            属性的类型
	 * @return
	 */
	private static Object getBindValue(HttpServletRequest request, String bindName, Class<?> bindType) {
		// 得到request中的值
		String value = request.getParameter(bindName);
		if (value != null) {
			value = value.trim().replace("\t", "").replace("\n", "");
		}
		return getBindValue(value, bindType);
	}

	/**
	 * 通过调用方法名(setXxxx)将值设置到属性中
	 * 
	 * @param classObject
	 *            实体类对象
	 * @param strMethodName
	 *            方法名(一般都是setXxxx)
	 * @param argsType
	 *            属性类型数组
	 * @param args
	 *            属性值数组
	 * @return
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	private static Object invokeMothod(Object classObject, String strMethodName, Class<?>[] argsType, Object[] args)
			throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		// 得到classObject这个类的方法
		Method concatMethod = classObject.getClass().getMethod(strMethodName, argsType);
		// 调用方法将classObject赋值到相应的属性
		return concatMethod.invoke(classObject, args);
	}

	/**
	 * 根据bindType类型的不同转成相应的类型值
	 * 
	 * @param value
	 *            String类型的值,要根据bindType类型的不同转成相应的类型值
	 * @param bindType
	 *            属性的类型
	 * @return
	 */
	private static Object getBindValue(String value, Class<?> bindType) {
		if(value == null)
			return null;
		String typeName = bindType.getName();
		// 依次判断各种类型并转换相应的值
		if (typeName.equals("java.lang.String"))
			return value.trim();
		if(typeName.equals("java.lang.Float"))
			return  new Float(value);
			
		if (typeName.equals("int"))
			return new Integer(value);
		
		if (typeName.equals("java.lang.Integer"))
			return new Integer(value);
		
		if (typeName.equals("boolean") || typeName.equals("java.lang.Boolean")){
			return new Boolean(value);
		}
		return value;
	}
	/**
	 if ((value == null) || (value.trim().length() == 0))  
            return null;  
        String typeName = bindType.getName();  
        //依次判断各种类型并转换相应的值  
        if (typeName.equals("java.lang.String"))  
            return value;  
        if (typeName.equals("int"))  
            return new Integer(value);  
        if (typeName.equals("long"))  
            return new Long(value);  
        if (typeName.equals("boolean"))  
            return new Boolean(value);  
        if (typeName.equals("float"))  
            return new Float(value);  
        if (typeName.equals("double"))  
            return new Double(value);  
        if (typeName.equals("java.math.BigDecimal")) {  
            if ("NaN.00".equals(value))  
                return new BigDecimal("0");  
            return new BigDecimal(value.trim());  
        }  
        if (typeName.equals("java.util.Date"))  
            //参考DateUtil.parseDateDayFormat方法,value如果是时间类型,必须是yyyy-MM-dd格式才能被识别  
            //请参考我的另一篇博客http://blog.csdn.net/bq1073100909/article/details/49472615  
            return DateUtil.parseDateDayFormat(value);  
        if (typeName.equals("java.lang.Integer"))  
            return new Integer(value);  
        if (typeName.equals("java.lang.Long")) {  
            return new Long(value);  
        }  
        if (typeName.equals("java.lang.Boolean")) {  
            return new Boolean(value);  
        }  
        return value;  
	 */
	
	public static void main(String[] args) {
		Method[] methods = DSBom.class.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			System.out.println(methods[i].getName());
		}
	}
}
add or edit
public String add() {
		String tf_id = res.getParameter(request, "tf_id", "");
		TestMachine obj = null;
		TestMachine test = (TestMachine) systemService.findObjectByHql("from TestMachine where tf_id ='" + tf_id + "'");
		if ("".equals(tf_id)) {
			obj = (TestMachine) DTOBuilder.getDTO(request, TestMachine.class);
			obj.setTf_id(UuidUtil.get32UUID());
			obj.setTf_inputmen(UserUtils.getUser(request).getTf_name());
			obj.setTf_flag("Y");
			obj.setTf_inputdate(sdf.format(new Date()));
			systemService.save(obj);
			return SUCCESS;
		} else {
			try {
				DTOBuilder.updateDTO(request, test);
				systemService.update(test);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return SUCCESS;
		}
	}

	public void updateFlag() {
		TestMachine test = (TestMachine) systemService
				.findObjectByHql("from TestMachine where tf_id = '" + res.getParameter(request, "tf_id", "") + "'");
		test.setTf_flag("N");
		systemService.update(test);
		try {
			response.sendRedirect("testMachineAction!list.action?flag=N");
		} catch (Exception e) {
			e.printStackTrace();
		}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值