com.common.util.mapper.ConvertUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.common.util.mapper.ConvertUtils.java

Source

/**
 * Copyright (c) 2005-2011 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: ConvertUtils.java 1575 2011-05-09 13:46:56Z calvinxiu $
 */
package com.common.util.mapper;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.common.util.ReflectionUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;

import com.google.common.collect.Lists;

/**
 * ?,:
 * 1. ?Dozer, ?.
 * 2. ?Apache Commons BeanUtils, ?.
 * 
 * @author calvin
 */
@SuppressWarnings("rawtypes")
public abstract class ConvertUtils {

    /**
     * ?Dozer?, ????Mapper?.
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();

    static {
        //??yyyy-MM-dd  yyyy-MM-dd HH:mm:ss
        registerDateConverter("yyyy-MM-dd,yyyy-MM-dd HH:mm:ss");
    }

    /**
     * Dozer?.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        return dozer.map(source, destinationClass);
    }

    /**
     * Dozer?List.
     */
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * Apache BeanUtils?.
     * 
     * @param value ?.
     * @param toType ?.
     */
    public static Object convertStringToObject(String value, Class<?> toType) {
        try {
            return org.apache.commons.beanutils.ConvertUtils.convert(value, toType);
        } catch (Exception e) {
            throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
        }
    }

    /**
     * Apache BeanUtilsConverter?,??,','
     */
    public static void registerDateConverter(String patterns) {
        DateConverter dc = new DateConverter();
        dc.setUseLocaleFormat(true);
        dc.setPatterns(StringUtils.split(patterns, ","));
        org.apache.commons.beanutils.ConvertUtils.register(dc, Date.class);
    }
}