【工具类】反射工具类:ReflectUtil(持续更新~~~)

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;

import javax.xml.bind.annotation.XmlElement;
import java.beans.BeanInfo;
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Reflect Util
 *
 * @author zrg
 */
@Slf4j
public class ReflectUtil {
    /**
     * Get modify content
     *
     * @param source             Original Object
     * @param target             Target Object
     * @param comparedProperties Specify Object Array
     * @param isCompareSuper     Compare super object
     * @return
     */
    public static String objectModifyContent(Object source, Object target, String[] comparedProperties, Boolean isCompareSuper) {
        StringBuilder modifyContent = new StringBuilder();
        if (null == source || null == target) {
            return "";
        }
        // Get source class
        Class<?> sourceClass = source.getClass();
        Field[] sourceFields = sourceClass.getDeclaredFields();

        if (isCompareSuper) {
            Field[] sourceSuperFields = sourceClass.getSuperclass().getDeclaredFields();
            List<Field> fieldList = new ArrayList<>(Arrays.asList(sourceFields));
            fieldList.addAll(Arrays.asList(sourceSuperFields));
            sourceFields = fieldList.toArray(new Field[0]);
        }

        for (Field srcField : sourceFields) {
            // Get srcField
            String srcName = srcField.getName();
            if (null == comparedProperties || (Arrays.asList(comparedProperties).contains(srcName))) {
                // Get srcField value
                Object srcFieldValue = getFieldValue(source, srcName, isCompareSuper);
                String srcValue = srcFieldValue == null ? "" : srcFieldValue.toString();
                // Get targetFiled value
                Object targetFieldValue = getFieldValue(target, srcName, isCompareSuper);
                String targetValue = targetFieldValue == null ? "" : targetFieldValue.toString();
                if (StringUtils.isEmpty(srcValue) && StringUtils.isEmpty(targetValue)) {
                    continue;
                }
                if (!srcValue.equals(targetValue)) {
                    String srcFieldAnnotationName = srcField.getAnnotation(XmlElement.class).name();
                    modifyContent.append(srcFieldAnnotationName)
                            .append("from:`")
                            .append(srcValue)
                            .append("`to:`")
                            .append(targetValue)
                            .append("`;");
                }
            }
        }
        return modifyContent.toString();
    }

    /**
     * Get filedName's value of object
     *
     * @param obj       Object
     * @param fieldName Field Name
     * @return fieldValue
     */
    private static Object getFieldValue(Object obj, String fieldName, Boolean isCompareSuper) {
        Object fieldValue = null;
        if (obj == null) {
            return null;
        }
        Method[] methods = obj.getClass().getDeclaredMethods();

        if (isCompareSuper) {
            Method[] sourceSuperMethods = obj.getClass().getSuperclass().getDeclaredMethods();
            List<Method> methodList = new ArrayList<>(Arrays.asList(methods));
            methodList.addAll(Arrays.asList(sourceSuperMethods));
            methods = methodList.toArray(new Method[0]);
        }

        for (Method method : methods) {
            String methodName = method.getName();
            if (!methodName.startsWith("get")) {
                continue;
            }
            if (methodName.startsWith("get") && methodName.substring(3).equalsIgnoreCase(fieldName)) {
                try {
                    fieldValue = method.invoke(obj);
                } catch (Exception e) {
                    log.error("Get value error, method name: {}", methodName);
                }
            }
        }
        return fieldValue;
    }
    /**
     * 设置对象的指定属性的值
     *
     * @param obj
     * @param name
     * @param value
     */
    public static void setObjectAttributeValue(Object obj, String name, Object value) {
        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(obj.getClass());
        } catch (IntrospectionException e) {
            return;
        }

        List<PropertyDescriptor> descriptors = Arrays.stream(beanInfo.getPropertyDescriptors())
                .filter(p -> !p.getName().equals("class") && !p.getName().equals("id"))
                .collect(Collectors.toList());

        for (PropertyDescriptor descriptor : descriptors) {
            try {
                Method writeMethod = descriptor.getWriteMethod();
                if (null != writeMethod && name.equals(descriptor.getName())) {
                    writeMethod.invoke(obj, ConvertUtils.convert(value, obj.getClass().getDeclaredField(name).getType()));
                }
            } catch (IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值