java 对象操作工具类 BeanUtils


public abstract class BeanUtils {

    private static final Logger LOG = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * Find a method with the given method name and the given parameter types, declared on the given class or one of its superclasses. Prefers public methods, but will return a protected, package
     * access, or private method too.
     * <p>
     * Checks {@code Class.getMethod} first, falling back to {@code findDeclaredMethod}. This allows to find public methods without issues even in environments with restricted Java security settings.
     * 
     * @param clazz      the class to check
     * @param methodName the name of the method to find
     * @param paramTypes the parameter types of the method to find
     * @return the Method object, or {@code null} if not found
     * @see Class#getMethod
     * @see #findDeclaredMethod
     */
    public static Method findMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            return findDeclaredMethod(clazz, methodName, paramTypes);
        }
    }

    /**
     * Find a method with the given method name and the given parameter types, declared on the given class or one of its superclasses. Will return a public, protected, package access, or private
     * method.
     * <p>
     * Checks {@code Class.getDeclaredMethod}, cascading upwards to all superclasses.
     * 
     * @param clazz      the class to check
     * @param methodName the name of the method to find
     * @param paramTypes the parameter types of the method to find
     * @return the Method object, or {@code null} if not found
     * @see Class#getDeclaredMethod
     */
    public static Method findDeclaredMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
        try {
            return clazz.getDeclaredMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            if (clazz.getSuperclass() != null) {
                return findDeclaredMethod(clazz.getSuperclass(), methodName, paramTypes);
            }
            return null;
        }
    }

    /**
     * Find a method with the given method name and minimal parameters (best case: none), declared on the given class or one of its superclasses. Prefers public methods, but will return a protected,
     * package access, or private method too.
     * <p>
     * Checks {@code Class.getMethods} first, falling back to {@code findDeclaredMethodWithMinimalParameters}. This allows for finding public methods without issues even in environments with
     * restricted Java security settings.
     * 
     * @param clazz      the class to check
     * @param methodName the name of the method to find
     * @return the Method object, or {@code null} if not found
     * @throws IllegalArgumentException if methods of the given name were found but could not be resolved to a unique method with minimal parameters
     * @see Class#getMethods
     * @see #findDeclaredMethodWithMinimalParameters
     */
    public static Method findMethodWithMinimalParameters(Class<?> clazz, String methodName) throws IllegalArgumentException {

        Method targetMethod = findMethodWithMinimalParameters(clazz.getMethods(), methodName);
        if (targetMethod == null) {
            targetMethod = findDeclaredMethodWithMinimalParameters(clazz, methodName);
        }
        return targetMethod;
    }

    /**
     * Find a method with the given method name and minimal parameters (best case: none), declared on the given class or one of its superclasses. Will return a public, protected, package access, or
     * private method.
     * <p>
     * Checks {@code Class.getDeclaredMethods}, cascading upwards to all superclasses.
     * 
     * @param clazz      the class to check
     * @param methodName the name of the method to find
     * @return the Method object, or {@code null} if not found
     * @throws IllegalArgumentException if methods of the given name were found but could not be resolved to a unique method with minimal parameters
     * @see Class#getDeclaredMethods
     */
    public static Method findDeclaredMethodWithMinimalParameters(Class<?> clazz, String methodName) throws IllegalArgumentException {

        Method targetMethod = findMethodWithMinimalParameters(clazz.getDeclaredMethods(), methodName);
        if (targetMethod == null && clazz.getSuperclass() != null) {
            targetMethod = findDeclaredMethodWithMinimalParameters(clazz.getSuperclass(), methodName);
        }
        return targetMethod;
    }

    /**
     * Find a method with the given method name and minimal parameters (best case: none) in the given list of methods.
     * 
     * @param methods    the methods to check
     * @param methodName the name of the method to find
     * @return the Method object, or {@code null} if not found
     * @throws IllegalArgumentException if methods of the given name were found but could not be resolved to a unique method with minimal parameters
     */
    public static Method findMethodWithMinimalParameters(Method[] methods, String methodName) throws IllegalArgumentException {

        Method targetMethod = null;
        int numMethodsFoundWithCurrentMinimumArgs = 0;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                int numParams = method.getParameterTypes().length;
                if (targetMethod == null || numParams < targetMethod.getParameterTypes().length) {
                    targetMethod = method;
                    numMethodsFoundWithCurrentMinimumArgs = 1;
                } else {
                    if (targetMethod.getParameterTypes().length == numParams) {
                        // Additional candidate with same length
                        numMethodsFoundWithCurrentMinimumArgs++;
                    }
                }
            }
        }
        if (numMethodsFoundWithCurrentMinimumArgs > 1) {
            throw new IllegalArgumentException("Cannot resolve method '" + methodName + "' to a unique method. Attempted to resolve to overloaded method with "
                    + "the least number of parameters, but there were " + numMethodsFoundWithCurrentMinimumArgs + " candidates.");
        }
        return targetMethod;
    }

    /**
     * Retrieve the JavaBeans {@code PropertyDescriptor}s of a given class.
     * 
     * @param clazz the Class to retrieve the PropertyDescriptors for
     * @return an array of {@code PropertyDescriptors} for the given class
     * @throws BeansException if PropertyDescriptor look fails
     */
    public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) {
        try {
            return Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Retrieve the JavaBeans {@code PropertyDescriptors} for the given property.
     * 
     * @param clazz        the Class to retrieve the PropertyDescriptor for
     * @param propertyName the name of the property
     * @return the corresponding PropertyDescriptor, or {@code null} if none
     * @throws BeansException if PropertyDescriptor lookup fails
     */
    public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName) {
        PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(clazz);
        for (PropertyDescriptor pd : propertyDescriptors) {
            if (pd.getName() == propertyName) {
                return pd;
            }
        }
        return null;

    }

    /**
     * Find a JavaBeans {@code PropertyDescriptor} for the given method, with the method either being the read method or the write method for that bean property.
     * 
     * @param method the method to find a corresponding PropertyDescriptor for
     * @return the corresponding PropertyDescriptor, or {@code null} if none
     * @throws BeansException if PropertyDescriptor lookup fails
     */
    public static PropertyDescriptor findPropertyForMethod(Method method) {
        PropertyDescriptor[] pds = getPropertyDescriptors(method.getDeclaringClass());
        for (PropertyDescriptor pd : pds) {
            if (method.equals(pd.getReadMethod()) || method.equals(pd.getWriteMethod())) {
                return pd;
            }
        }
        return null;
    }

    /**
     * Determine the bean property type for the given property from the given classes/interfaces, if possible.
     * 
     * @param propertyName the name of the bean property
     * @param beanClasses  the classes to check against
     * @return the property type, or {@code Object.class} as fallback
     */
    public static Class<?> findPropertyType(String propertyName, Class<?>... beanClasses) {
        if (beanClasses != null) {
            for (Class<?> beanClass : beanClasses) {
                PropertyDescriptor pd = getPropertyDescriptor(beanClass, propertyName);
                if (pd != null) {
                    return pd.getPropertyType();
                }
            }
        }
        return Object.class;
    }

    public static <T> T convertPojo(Object orig, Class<T> targetClass) {
        T target = null;
        try {
            target = targetClass.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(orig, target);
        } catch (BeansException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            return target;
        }
    }

    public static void copyPropertiesNotNull(Object source, Object target) {
        copyPropertiesNotNull(source, target, null, (String[]) null);
    }

    /**
     * Copy the property values of the given source bean into the given target bean.
     * <p>
     * Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target
     * bean does not will silently be ignored.
     * 
     * Properties content is not null @author jh
     * 
     * @param source           the source bean
     * @param target           the target bean
     * @param editable         the class (or interface) to restrict property setting to
     * @param ignoreProperties array of property names to ignore
     * @throws BeansException if the copying failed
     * @see BeanWrapper
     */
    private static void copyPropertiesNotNull(Object source, Object target, Class<?> editable, String... ignoreProperties) {
        try {
            if (source == null || target == null) {
                throw new Exception("source or target is null!");
            }
            Class<?> actualEditable = target.getClass();
            if (editable != null) {
                if (!editable.isInstance(target)) {
                    throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
                }
                actualEditable = editable;
            }

            PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
            List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

            for (PropertyDescriptor targetPd : targetPds) {
                Method writeMethod = targetPd.getWriteMethod();
                if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
                    PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                    if (sourcePd != null) {
                        Method readMethod = sourcePd.getReadMethod();
                        if (readMethod != null && writeMethod.getParameterTypes()[0].isAssignableFrom(readMethod.getReturnType())) {
                            try {
                                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                    readMethod.setAccessible(true);
                                }
                                Object value = readMethod.invoke(source);
                                if (null != value) {// 属性非空则复制
                                    if (value instanceof Integer) {
//                                        if ((Integer) value != 0) {
                                            writeObject(target, writeMethod, value);
//                                        }
                                    } else if (value instanceof Double) {
//                                        if ((Double) value != 0d) {
                                            writeObject(target, writeMethod, value);
//                                        }
                                    } else if (value instanceof Long) {
//                                        if ((Long) value != 0l) {
                                            writeObject(target, writeMethod, value);
//                                        }
                                    } else if (value instanceof String) {
//                                        if (null != value) {
                                            writeObject(target, writeMethod, value);
//                                        }
                                    } else if (value instanceof Float) {
//                                        if ((Float) value != 0f) {
                                            writeObject(target, writeMethod, value);
//                                        }
                                    } else if (value instanceof Boolean) {
//                                        if ((Boolean) value != null) {
                                            writeObject(target, writeMethod, value);
//                                        }
                                    } else if (value instanceof Date) {
//                                        if ((Date) value != null) {
                                            writeObject(target, writeMethod, value);
//                                        }
                                    } else {// 其他类型
                                        writeObject(target, writeMethod, value);
                                    }
                                }
                            } catch (Throwable ex) {
                                throw new Exception("Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeObject(Object target, Method writeMethod, Object value) throws IllegalAccessException, InvocationTargetException {
        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
            writeMethod.setAccessible(true);
        }
        writeMethod.invoke(target, value);
    }

    /**
     * 判断类中是否有该属性,如果存在,返回其对应的字段,否则返回null
     * 
     * @param attr  类属性
     * @param Clazz 对应的实体类
     * @return 返回其对应的数据库字段
     */
    public static boolean existColumn(String attr, Class Clazz) {
        try {
            Field field = Clazz.getDeclaredField(attr);
            return null != field;
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            return false;
        }
        return false;
    }

    public static Object fromRequest(HttpServletRequest request, Class clazz) {
        Map map = request.getParameterMap();
        Object result = null;
        try {
            result = fromMap(map, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 
     * 传入map,实例化成对象
     * 
     * @param <T>
     * 
     * @Author: jianghan
     * @param map
     * @param clazz
     * @return
     */
    public static <T> T fromMap(Map map, Class<T> clazz) {
        try {
            T result = clazz.newInstance();
            Field[] fieldsParent = clazz.getSuperclass().getDeclaredFields();
            Method method;
            for (Field field : fieldsParent) {
                field.setAccessible(true);
                field.set(result, getValue(field, map));
                field.setAccessible(false);
            }
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                field.set(result, getValue(field, map));
                field.setAccessible(false);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // private static String createSetMethod(String attr) {
    // return "set" + Character.toUpperCase(attr.charAt(0)) + attr.substring(1);
    // }

    private static Object getValue(Field field, Map<String, Object> map) {
        Object value = map.get(field.getName());
        if (value == null || value.equals("null")) {
            if ((field.getType().equals(Boolean.TYPE)) || (field.getType().equals(Boolean.class))) {
                return false;
            }
            if ((field.getType().equals(int.class))) {
                return 0;
            }
            return null;
        }
        if ((value instanceof String[])) {
            value = ((String[]) value)[0];
        }
        if (field.getType().equals(String.class))
            return value;
        if ((field.getType().equals(Integer.TYPE)) || (field.getType().equals(Integer.class)))
            return Integer.valueOf(Integer.parseInt(value.toString()));
        if ((field.getType().equals(Long.TYPE)) || (field.getType().equals(Long.class)))
            return Long.valueOf(Long.parseLong(value.toString()));
        if ((field.getType().equals(Short.TYPE)) || (field.getType().equals(Short.class)))
            return Short.valueOf(Short.parseShort(value.toString()));
        if ((field.getType().equals(Byte.TYPE)) || (field.getType().equals(Byte.class)))
            return Byte.valueOf(Byte.parseByte(value.toString()));
        if ((field.getType().equals(Float.TYPE)) || (field.getType().equals(Float.class)))
            return Float.valueOf(Float.parseFloat(value.toString()));
        if ((field.getType().equals(Double.TYPE)) || (field.getType().equals(Double.class)))
            return Double.valueOf(Double.parseDouble(value.toString()));
        if ((field.getType().equals(Boolean.TYPE)) || (field.getType().equals(Boolean.class)))
            return Boolean.valueOf(value.toString());
        if (field.getType().equals(Date.class)) {
            return new Date(Long.parseLong(value.toString()));
        }
        if (field.getType().equals(List.class)) {
            RedisParam att = field.getAnnotation(RedisParam.class);
            return JSONArray.parseArray(value.toString(), att.value());
        }
        LOG.error("缺少数据库映射类型-->" + field.getType().toString());
        return value;
    }

    public static JSONObject toJsonObject(Entity e) {
        JSONObject jo = JsonUtil.jsonObject();
        try {
            Class<? extends Entity> c = e.getClass();
            Field[] fs = c.getDeclaredFields();
            for (Field field : fs) {
                field.setAccessible(true);
                jo.put(field.getName(), field.get(e));
                field.setAccessible(false);
            }
        } catch (SecurityException e1) {
            e1.printStackTrace();
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }
        return jo;
    }
}

package com.xj.hhjk.common.util;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xj.hhjk.common.annotation.RedisParam;
import com.xj.hhjk.common.base.Entity;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长青风

赏一块,发大财!赏两块,惹人爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值