码迷,mamicode.com
首页 > 其他好文 > 详细

Bean 工具类

时间:2020-10-29 10:36:06      阅读:17      评论:0      收藏:0      [点我收藏+]

标签:OLE   break   map   final   equals   esc   value   rabl   bytearray   

import java.beans.BeanInfo;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.Id;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jmx.access.InvocationFailureException;

import cn.com.amway.msgcenter.console.repository.AppCustomFieldMapper;
import cn.com.amway.msgcenter.console.repository.BeanComparisionResult;
import cn.com.amway.msgcenter.console.repository.ComparableField;
import cn.com.amway.msgcenter.console.repository.DescribeField;

public abstract class BeanUtil {
private static Logger logger = LoggerFactory.getLogger(BeanUtil.class);
private static Mapper mapper = new DozerBeanMapper();

static {
    ((DozerBeanMapper) mapper).setCustomFieldMapper(new AppCustomFieldMapper());
}

public static <T> T getMappedObject(Object orig, Class<T> destClazz) {
    T destObj = mapper.map(orig, destClazz);
    return destObj;
}

public static <T> List<T> getMappedObjectList(List<?> origList, Class<T> destClazz) {

    if (CollectionUtil.isEmpty(origList)) {
        return Collections.emptyList();
    }

    List<T> destObjList = new ArrayList<T>();
    for (Object orig : origList) {
        destObjList.add(getMappedObject(orig, destClazz));
    }

    return destObjList;
}

public static void copyProperties(Object orig, Object dest) {
    mapper.map(orig, dest);
}

public static void copyProperties(final Object orig, final Object dest, final String... excludedFields) {
    Map<String, Object> destFieldNameValueHash = null;
    PropertyDescriptor[] descriptors = null;
    if (!ArrayUtil.isEmpty(excludedFields)) {
        destFieldNameValueHash = new HashMap<String, Object>();
        for (int i = 0; i < excludedFields.length; i++) {
            destFieldNameValueHash.put(excludedFields[i], null);
        }
        int destFieldNameValueHashSize = destFieldNameValueHash.size();

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(dest.getClass());
            if (beanInfo != null) {
                descriptors = beanInfo.getPropertyDescriptors();
                String fieldName = null;
                int numOfSettedFields = 0;
                for (PropertyDescriptor each : descriptors) {
                    fieldName = each.getName();
                    if (destFieldNameValueHash.containsKey(fieldName)) {
                        Method read = each.getReadMethod();
                        Object value = read.invoke(dest, new Object[0]);
                        destFieldNameValueHash.put(fieldName, value);
                        if (destFieldNameValueHashSize == ++numOfSettedFields) {
                            break;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("Unnable to save the value of fields of" + dest.getClass().getName(), ex);
        }
    }

    mapper.map(orig, dest);

    if (destFieldNameValueHash != null) {
        String fieldName = null;
        for (PropertyDescriptor each : descriptors) {
            fieldName = each.getName();
            if (destFieldNameValueHash.containsKey(fieldName)) {
                Method write = each.getWriteMethod();
                try {
                    write.invoke(dest, destFieldNameValueHash.get(fieldName));
                } catch (Exception ex) {
                    logger.error("Unnable to restore the value of fields of" + dest.getClass().getName(), ex);
                }
            }
        }
    }

}

public static <T extends Serializable> T deepCopy(T t) throws IOException, ClassNotFoundException {
    // Write the object out to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(t);
    out.flush();
    out.close();

    // Retrieve an input stream from the byte array and read
    // a copy of the object back in.
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bis);
    @SuppressWarnings("unchecked")
    T copy = (T) in.readObject();

    return copy;
}

/**
 * Fetch property value of the bean which annotated with @id on getter method
 * 
 * @throws InvocationFailureException
 */
public static Serializable getAnnotatedId(Object bean) {
    Serializable id = getAnnotatedIdFromMethod(bean);
    if (id == null) id = getAnnotatedIdFromField(bean.getClass(), bean);

    return id;
}

private static Serializable getAnnotatedIdFromMethod(Object bean) {
    Serializable id = null;
    Class<?> clazz = bean.getClass();
    Method[] methods = clazz.getMethods();
    if (!ArrayUtil.isEmpty(methods)) {
        for (Method method : methods) {
            Id idAnnotation = method.getAnnotation(Id.class);

            if (idAnnotation != null) {
                try {
                    id = (Serializable) method.invoke(bean);
                    return id;
                } catch (Exception e) {
                    throw new InvocationFailureException("Could not invoke get id method");
                }
            }
        }
    }

    return null;
}

private static Serializable getAnnotatedIdFromField(Class<?> clazz, Object bean) {
    Serializable id = null;
    Field[] fields = clazz.getDeclaredFields();
    if (!ArrayUtil.isEmpty(fields)) {
        for (Field field : fields) {
            Id idAnnotation = field.getAnnotation(Id.class);
            if (idAnnotation != null) {
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    Method read = pd.getReadMethod();
                    id = (Serializable) read.invoke(bean, new Object[0]);
                    return id;
                } catch (Exception e) {
                    throw new InvocationFailureException("Could not invoke get id method");
                }

            }
        }
    }

    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz != null && !(superClazz.equals(Object.class))) {
        id = getAnnotatedIdFromField(superClazz, bean);
        if (id != null) return id;

    }

    return null;
}

/**
 * Fetch all properties value from java bean object
 * 
 * @param bean
 * @return property class as key, property value as value
 * @throws IntrospectionException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public Map<Class<?>, Object> getPropertiesClassValueHash(Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Map<Class<?>, Object> result = new HashMap<Class<?>, Object>();
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
    if (beanInfo != null) {
        PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        Class<?> clazz = null;
        for (PropertyDescriptor each : descriptors) {
            clazz = each.getPropertyType();

            Method read = each.getReadMethod();
            Object obj = read.invoke(bean, new Object[0]);
            result.put(clazz, obj);
        }
    }

    return result;
}

public static String toXml(Object obj) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(out);
    encoder.writeObject(obj);
    encoder.close();
    try {
        return new String(out.toByteArray(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.error("Unable convert xml to Object", e);
        return null;
    }
}

public static Object fromXml(String xml) {
    ByteArrayInputStream in;
    XMLDecoder decoder = null;
    try {
        in = new ByteArrayInputStream(xml.trim().getBytes("UTF-8"));
        decoder = new XMLDecoder(in);
        Object obj = decoder.readObject();
        return obj;
    } catch (UnsupportedEncodingException e) {
        logger.error("Unable convert xml to Object", e);
    } finally {
        if (decoder != null) decoder.close();
    }

    return null;
}

/**
 * To compare all fields what has annotation "ComparableField" Or "DescribeField" of two beans.
 * if the field name is same return the result of value is different.
 * 
 * @param oriBean
 * @param compareBean
 * @return All different fields what‘s field name is same and field value is different. The key
 *         of Map is field name.
 * @throws Exception
 */
public static Map<String, BeanComparisionResult> compareBean(Object oriBean, Object compareBean) throws Exception {
    if (oriBean == null || compareBean == null)
        throw new NullPointerException("oriBean or compareBean is null, could not compare bean properties");

    Set<Class<? extends Annotation>> annotationClasses = new HashSet<Class<? extends Annotation>>();
    annotationClasses.add(ComparableField.class);
    annotationClasses.add(DescribeField.class);
    Set<String> comparableFields = getAnnotatedFields(oriBean.getClass(), annotationClasses);
    if (comparableFields.size() <= 0) return new HashMap<String, BeanComparisionResult>(0);

    Map<String, BeanComparisionResult> result = new HashMap<String, BeanComparisionResult>();
    BeanInfo beanInfo = Introspector.getBeanInfo(oriBean.getClass());

    for (PropertyDescriptor prop : beanInfo.getPropertyDescriptors()) {
        String fieldName = prop.getName();
        String dateTimeFormat = getDateTimeFormatByAnnotation(oriBean, fieldName);
        if (!StringUtil.isEmpty(fieldName) && comparableFields.remove(fieldName)) {
            Method getter = prop.getReadMethod();
            Object oriBeanFieldValue = getter.invoke(oriBean);
            Object compareBeanFieldValue = getter.invoke(compareBean);
            if (!StringUtil.isEmpty(dateTimeFormat)) {
                SimpleDateFormat sdf = new SimpleDateFormat(dateTimeFormat);
                String oriBeanFieldValueDate = oriBeanFieldValue != null ? sdf.format(oriBeanFieldValue) : null;
                String compareBeanFieldValueDate =
                        compareBeanFieldValue != null ? sdf.format(compareBeanFieldValue) : null;
                if (oriBeanFieldValueDate == compareBeanFieldValueDate
                        || (oriBeanFieldValueDate != null && oriBeanFieldValueDate
                                .equals(compareBeanFieldValueDate))) {
                    continue;
                } else {
                    BeanComparisionResult bcr = new BeanComparisionResult();
                    bcr.setDifferentFieldName(fieldName);
                    bcr.setOriFieldValue(compareBeanFieldValueDate);
                    bcr.setToCompareFieldValue(compareBeanFieldValueDate);
                    result.put(fieldName, bcr);
                }
            } else {
                if (oriBeanFieldValue == compareBeanFieldValue
                        || (oriBeanFieldValue != null && oriBeanFieldValue.equals(compareBeanFieldValue))) {
                    continue;
                } else {
                    BeanComparisionResult bcr = new BeanComparisionResult();
                    bcr.setDifferentFieldName(fieldName);
                    bcr.setOriFieldValue(oriBeanFieldValue);
                    bcr.setToCompareFieldValue(compareBeanFieldValue);
                    result.put(fieldName, bcr);
                }
            }
        }
    }

    return result;
}

public static Object getFieldValue(Object obj, String fieldName) {
    Object value = null;
    Class<?> clazz = obj.getClass();
    try {
        PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);
        value = pd.getReadMethod().invoke(obj, new Object[0]);
    } catch (Exception e) {
        logger.error("Unable to get field ‘" + fieldName + "‘ value from " + clazz.getName(), e);
    }

    return value;
}

private static String getDateTimeFormatByAnnotation(Object oriBean, String fieldName) {
    String dateTimeFormat = "";
    Field[] fields = oriBean.getClass().getDeclaredFields();
    if (!ArrayUtil.isEmpty(fields)) {
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                DescribeField desc = field.getAnnotation(DescribeField.class);
                if (desc != null && !StringUtil.isEmpty(desc.dateTimeFormat())) {
                    dateTimeFormat = desc.dateTimeFormat();
                    break;
                }
            }
        }
    }
    return dateTimeFormat;
}

private static Set<String> getAnnotatedFields(Class<?> beanClass, Set<Class<? extends Annotation>> annotationClasses) {
    Set<String> result = new HashSet<String>();
    Class<?> clazz;
    try {
        clazz = beanClass.getClassLoader().loadClass(beanClass.getName());
    } catch (ClassNotFoundException e) {
        logger.error("Cannot load class ‘" + beanClass.getName() + "‘", e);
        return null;
    }
    Field[] fields = clazz.getDeclaredFields();
    if (!ArrayUtil.isEmpty(fields)) {
        for (Field field : fields) {
            innerloop: for (Class<? extends Annotation> annotationClass : annotationClasses) {
                if (field.isAnnotationPresent(annotationClass)) {
                    result.add(field.getName());
                    break innerloop;
                }
            }
        }
    }

    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz != null && !(superClazz.equals(Object.class))) {
        result.addAll(getAnnotatedFields(superClazz, annotationClasses));
    }

    return result;
}

/**
 * 对象转String,目前只支持BigInteger 转 String, 其他 直接返回对象的toString()
 * 
 * @param obj
 * @return
 */
public static String convertObjectToString(Object obj) {
    if (obj != null) {
        if (obj instanceof BigInteger) {
            BigInteger intB = (BigInteger) obj;
            return intB.toString();
        }
    } else {
        return "";
    }
    return String.valueOf(obj);
}

}

Bean 工具类

标签:OLE   break   map   final   equals   esc   value   rabl   bytearray   

原文地址:https://blog.51cto.com/7218743/2544683

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!