自定义对象数据替换其字段值

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据操作工具类
 * @author xuyang
 * @time 2016/11/10 15:58
 */
public class DataHelper {
    /**
     * 替换对象的字段数据(对象类型必须相同)
     * @param sourceObject 被替换的源数据对象 replaceObject 替换的数据对象
     * @return Object 替换后的数据对象
     * @author xuyang
     * @time 2016/11/10 15:58
     */
    public static <T> T updateObject(T sourceObject,T replaceObject){
        Class<?> sourceClazz = sourceObject.getClass();
        Field[] sourceFields = sourceClazz.getDeclaredFields();

        Class<?> replaceClazz = sourceObject.getClass();
        Field[] replaceFields = replaceClazz.getDeclaredFields();

        try {
            for (int i = 0;i < replaceFields.length;i++){
                Field replaceField = replaceFields[i];
                replaceField.setAccessible(true);
                //字段子更新赋值判断
                if (null != replaceField.get(replaceObject)) {
                    Field sourceField = sourceFields[i];
                    sourceField.setAccessible(true);
                    sourceField.set(sourceObject,replaceField.get(replaceObject));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sourceObject;
    }

    /**
     * 替换对象的字段数据(对象类型可以不同,只替换同类型同字段名的字段值)
     * @param sourceObject 被替换的源数据对象 replaceObject 替换的数据对象
     * @return Object 替换后的数据对象
     * @author xuyang
     * @time 2016/11/10 15:58
     */
    public static <T> T updateDifObject(T sourceObject,Object replaceObject){
        Class<?> sourceClazz = sourceObject.getClass();
        Field[] sourceFields = sourceClazz.getDeclaredFields();

        Class<?> replaceClazz = replaceObject.getClass();
        Field[] replaceFields = replaceClazz.getDeclaredFields();

        try {
            for (int i = 0;i < replaceFields.length;i++){
                Field replaceField = replaceFields[i];
                replaceField.setAccessible(true);
                //字段子更新赋值判断
                if (null != replaceField.get(replaceObject)) {
                    for (int j = 0; j < sourceFields.length; j++) {
                        Field sourceField = sourceFields[j];
                        if(sourceField.getName().equals(replaceField.getName())
                                && sourceField.getType().getName().equals(replaceField.getType().getName())){
                            sourceField.setAccessible(true);
                            sourceField.set(sourceObject,replaceField.get(replaceObject));
                            break;
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sourceObject;
    }


    /**
     * 判断对象某些值是否为空
     * @param object
     * @param <T>
     * @return
     * @author gaoliubei
     */
    public static <T> String verify(T object,String[] needVerify)
    {
        Class<?> sourceClazz = object.getClass();
        Field [] fields = sourceClazz.getDeclaredFields();
        StringBuilder result = new StringBuilder();
        boolean isLegal = true;
        for (int i = 0;i < fields.length;i++)
        {
            Field field = fields[i];
            field.setAccessible(true);
            try {
                Object value = field.get(object);
                if (value == null)
                {

                    String filedName = field.getName();
                    boolean isd = false;
                    for (int j = 0;j < needVerify.length; j++)
                    {
                        String isResult = needVerify[j];
                        if (isResult == filedName)
                        {
                            isLegal = false;
                            isd = true;
                            break;
                        }
                    }

                    if (isd)
                    {
                        result.append(filedName+" : 不能为空 ");
                    }

                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if (!isLegal)
        {
            return result.toString();
        }
        return null;
    }

    /**
     * map转对象
     * @param map
     * @param beanClass
     * @return
     * @throws Exception
     */
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) {
        try {
            if (map == null)
                return null;

            Object obj = beanClass.newInstance();

            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                Method setter = property.getWriteMethod();
                if (setter != null) {
                    setter.invoke(obj, map.get(property.getName()));
                }
            }

            return obj;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对象转map
     * @param obj
     * @return
     */
    public static Map<?, ?> objectToMap(Object obj) {
        try {
            if(obj == null)
                return null;

            Map<String, Object> map = new HashMap<String, Object>();

            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (key.compareToIgnoreCase("class") == 0) {
                    continue;
                }
                Method getter = property.getReadMethod();
                Object value = getter!=null ? getter.invoke(obj) : null;
                map.put(key, value);
            }

            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想对不同返回对象中的不同属性添加自定义注解,并且只对有自定义注解字段进行数据字典的格式化,你可以使用反射来实现。下面是一个示例的 Java 代码: 首先,你需要定义一个自定义注解 `DataDictionaryField`,用于标记需要进行数据字典格式化的字段: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface DataDictionaryField { } ``` 接下来,你需要修改 `DataDictionary` 类,使其能够根据字段上的自定义注解进行格式化操作: ```java import org.springframework.stereotype.Component; import java.lang.reflect.Field; import java.util.HashMap; @Component public class DataDictionary { private HashMap<String, String> dictionary; public DataDictionary() { dictionary = new HashMap<>(); // 添加键对到数据字典 dictionary.put("name", "John"); dictionary.put("age", "25"); dictionary.put("city", "New York"); } public String getValue(String key) { // 检查数据字典中是否包含指定的键 if (dictionary.containsKey(key)) { // 获取指定键的 return dictionary.get(key); } else { return null; } } public void formatObject(Object obj) { // 获取对象的类 Class<?> clazz = obj.getClass(); // 获取所有字段 Field[] fields = clazz.getDeclaredFields(); // 遍历字段 for (Field field : fields) { // 检查字段是否有 DataDictionaryField 注解 if (field.isAnnotationPresent(DataDictionaryField.class)) { // 设置字段可访问 field.setAccessible(true); try { // 获取字段 Object value = field.get(obj); if (value instanceof String) { // 根据数据字典进行格式化操作 String formattedValue = getValue((String) value); if (formattedValue != null) { // 将格式化后的设置回字段 field.set(obj, formattedValue); } } } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } ``` 在上述代码中,我们修改了 `DataDictionary` 类,添加了一个新的方法 `formatObject`,用来根据字段上的自定义注解进行格式化操作。在该方法中,我们首先获取对象的类和所有字段,然后遍历字段,检查字段是否有 `DataDictionaryField` 注解。如果有注解,我们将字段设置为可访问,并获取字段。如果是 `String` 类型,并且存在对应的数据字典,我们将格式化后的设置回字段。 最后,你可以在切面类中调用 `DataDictionary` 类的 `formatObject` 方法来进行格式化操作: ```java import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Aspect @Component public class ReturnValueFormattingAspect { @Autowired private DataDictionary dataDictionary; @Pointcut("execution(* com.example.YourService.*(..))") public void serviceMethods() {} @AfterReturning(pointcut = "serviceMethods()", returning = "returnValue") public void formatReturnValue(Object returnValue) { dataDictionary.formatObject(returnValue); } } ``` 在上述代码中,我们在切面类的 `formatReturnValue` 方法中调用了 `DataDictionary` 类的 `formatObject` 方法,将返回对象作为参数传递给它进行格式化操作。 请注意,上述代码中的 `com.example.YourService.*(..)` 部分需要替换为你实际项目中的服务类和方法的包名和方法名。 希望这个示例能帮助到你在 Spring Cloud 项目中根据自定义注解对返回对象中的字段进行数据字典的格式化。请根据你的具体场景进行调整和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值