各种格式化-BeanUtils mapToBean requestTobean 含有类型转换

来源:互联网 发布:淘宝法莎莉雅手办 编辑:程序博客网 时间:2024/06/05 02:09
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

public class BeanOperatorUtils {

    private final static SimpleDateFormat sfyyyyMMddHHmmss = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    private final static SimpleDateFormat sfyyyyMMdd = new SimpleDateFormat(
            "yyyy-MM-dd");

    public static <T> T request2BeanAndConvertType(HttpServletRequest request,
            Class<T> c) throws InstantiationException, IllegalAccessException,
            InvocationTargetException {
        T o = c.newInstance();
        Field[] fields = c.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {

            String fieldName = fields[i].getName();

            //将这改成从map中取值就可以实现,mapTobean的转换

            String value = request.getParameter(fieldName);
            if(null == value) continue;
            Object newValue = toType(value,fields[i].getType());
            //System.out.println("1fieldName="+fieldName+" ; 1value="+value+" ; newValue="+newValue+" ;type="+fields[i].getType());

            if(null == newValue) continue;

            // 将转换后的值转移到bean中

            BeanUtils.copyProperty(    o,fieldName,newValue);
        }
        return o;
    }

    public static void main(String[] args) throws IllegalAccessException,
            InvocationTargetException, InstantiationException {


    }
    //将值得类型进行装换
    public static Object toType(String s, Class c) {
        if (null == s) {
            return null;
        }
        if (c == String.class) {
            return s;
        }
        if (c == int.class) {
            return Integer.parseInt(s);
        }
        if (c == Integer.class) {
            return Integer.valueOf(s);
        }
        if (c == long.class) {
            return Long.parseLong(s);
        }
        if (c == Long.class) {
            return Long.valueOf(s);
        }
        if (c == double.class) {
            return Double.parseDouble(s);
        }
        if (c == Double.class) {
            return Double.valueOf(s);
        }
        if (c == char.class) {
            return s.charAt(0);
        }
        if (c == Date.class) {
            try {
                if (s.length() == 19) {
                    return sfyyyyMMddHHmmss.parse(s);
                }
                if (s.length() == 10) {
                    return sfyyyyMMdd.parse(s);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

  
}

1 0
原创粉丝点击