CGLIB基于一个已有类动态生成一个子类bean(转)
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.3</version> </dependency>
转载:http://www.zzvips.com/article/182396.html
根据旧对象生成一个新对象,且新对象的类是旧对象的所属类的子类
import com.alibaba.fastjson.JSON; import net.sf.cglib.beans.BeanGenerator; import net.sf.cglib.beans.BeanMap; import org.apache.commons.beanutils.PropertyUtilsBean; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; /** * @Author : wangbin * @Date : 2023/3/13 16:04 * @Description: 从一个旧对象生成一个新对象 */ 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); } /** * bean 添加属性和值 * * @param property * @param value */ public void setValue(String property, Object value) { beanMap.put(property, value); } /** * 获取属性值 * * @param property * @return */ public Object getValue(String property) { return beanMap.get(property); } /** * 获取对象 * * @return */ public Object getTarget() { return this.target; } /** * 根据属性生成对象 * * @param superclass * @param propertyMap * @return */ 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(); } public static Object getTarget(Object dest, Map<String, Object> addProperties) { // 获取属性map PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest); Map<String, Class> propertyMap = new HashMap<>(); for (PropertyDescriptor d : descriptors) { if (!"class".equalsIgnoreCase(d.getName())) { propertyMap.put(d.getName(), d.getPropertyType()); } } // 添加新属性 addProperties.forEach((k, v) -> propertyMap.put(k, v.getClass())); // 创建动态bean DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap); // 给bean添加旧数据 propertyMap.forEach((k, v) -> { try { if (!addProperties.containsKey(k)) { dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k)); } } catch (Exception e) { e.printStackTrace(); } }); // 添加新数据 addProperties.forEach((k, v) -> { try { dynamicBean.setValue(k, v); } catch (Exception e) { e.printStackTrace(); } }); return dynamicBean.getTarget(); } public static void main(String[] args) { User entity = new User(); entity.setName("eee"); entity.setAge(222); Map<String, Object> addProperties = new HashMap<>() {{ put("newKey", "newVal"); }}; User finalPicBaseReqVo = (User) getTarget(entity, addProperties); System.out.println(JSON.toJSONString(finalPicBaseReqVo)); } }