• java动态给实体类添加属性


     


    需要的jar包有两个: cglib-3.1.jar 和 google-collections-1.0.jar 
    如果是maven项目,就不需要cglib-3.1.jar,直接用spring自带的 org.springframework.cglib即可。 
    1、创建一个实体:DynamicBean
    public class DynamicBean {
    
        private Object target;
        private BeanMap beanMap;
    
        public DynamicBean(Class superclass, Map<String, Class> propertyMap) {
            this.target = generateBean(superclass, propertyMap);
            this.beanMap = BeanMap.create(this.target);
        }
    
        public void setValue(String property, Object value) {
            beanMap.put(property, value);
        }
    
        public Object getValue(String property) {
            return beanMap.get(property);
        }
    
        public Object getTarget() {
            return this.target;
        }
        /**
         * 根据属性生成对象
         *
         */
        private Object generateBean(Class superclass, Map<String, Class> propertyMap) {
            BeanGenerator generator = new BeanGenerator();
            if (null != superclass) {
                generator.setSuperclass(superclass);
            }
            BeanGenerator.addProperties(generator, propertyMap);
            return generator.create();
        }
    }
    
    

    2、创建映射类,用来生成动态bean

    public class ReflectUtil {
    	private static Logger logger = LoggerFactory.getLogger(ReflectUtil.class);
    	
    	public static Object getObject(Object dest, Map<String, Object> addProperties) {
    	    PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
    	    PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest);
    	    Map<String, Class> propertyMap = Maps.newHashMap();
    	    for (PropertyDescriptor d : descriptors) {
    	        if (!"class".equalsIgnoreCase(d.getName())) {
    	            propertyMap.put(d.getName(), d.getPropertyType());
    	        }
    	    }
    	    addProperties.forEach((k, v) -> {
    	    	String sclass = v.getClass().toString();
    	    	if(sclass.equals("class java.util.Date")) {//对日期进行处理
    	    		propertyMap.put(k, Long.class);
    	    	}else {
    	    		propertyMap.put(k, v.getClass());
    	    	}
    	    	
    	    });
    	    DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap);
    	    propertyMap.forEach((k, v) -> {
    	        try {
    	            if (!addProperties.containsKey(k)) {
    	                dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k));
    	            }
    	        } catch (Exception e) {
    	            logger.error("动态添加字段出错", e);
    	        }
    	    });
    	    addProperties.forEach((k, v) -> {
    	        try {
    	        	String sclass = v.getClass().toString();
    		    	if(sclass.equals("class java.util.Date")) {//动态添加的字段为date类型需要进行处理
    		    		Date date = (Date) v;
    		    		dynamicBean.setValue(k, date.getTime());
    		    	}else {
    		    		dynamicBean.setValue(k, v);
    		    	}
    	        } catch (Exception e) {
    	        	logger.error("动态添加字段值出错", e);
    	        }
    	    });
    	    Object obj = dynamicBean.getTarget();
    	    return obj;
    	}
    }
    
    

    3、使用方法
    现有一个用户实体User:

    public class User {
    
    	private String name;
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    	
    }
    

    User只有一个name属性,现在要动态的为User添加年龄属性,代码如下:

    public static void main(String[] args) {
    		User user = new User();
    		user.setName("Daisy");
    		System.out.println("User:"+JSON.toJSONString(user));
    		Map<String,Object> propertiesMap = new HashMap<String,Object>();
    		propertiesMap.put("age", 18);
    		Object obj = ReflectUtil.getTarget(user, propertiesMap);
    		System.out.println("动态为User添加age之后,User:"+JSON.toJSONString(obj));
    }
     

    打印结果如下:

    User:{"name":"Daisy"}
    动态为User添加age之后,User:{"age":18,"name":"Daisy"}
  • 相关阅读:
    C# API 大全
    也说_T、_TEXT、TEXT、L
    项脊轩志--归有光
    C# tostring()汇总
    StructLayout特性
    关于C#静态构造函数的几点说明
    C#生成DLL文件
    做.net的早晚会用到,并且网上还没有这方面的正确资料或几乎很少
    C# 实现屏幕键盘 (ScreenKeyboard)
    Microsoft .NET Native
  • 原文地址:https://www.cnblogs.com/wcss/p/13827563.html
Copyright © 2020-2023  润新知