Cglib动态创建对象

1.需要用到的包:springboot自带呢....

2.使用案例:

public class Main {
    public static void main(String[] args) throws JsonProcessingException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //Cglib动态生成对象
        //创建Bean构造器
        BeanGenerator beanGenerator = new BeanGenerator();
        //准备对象数据,用于构造类
        Map<String,Class> map = new HashMap<>();
        map.put("id",Integer.class);
        map.put("name",String.class);
        //遍历Map,添加属性
        for (Map.Entry entry : map.entrySet()){
            //当然也可以直接使用Map数据获取value的class设置进去
            //如map.put("id",1); entry.getValue().getClass();
            beanGenerator.addProperty(entry.getKey().toString(), (Class) entry.getValue());
        }
        //创建对象
        Object object = beanGenerator.create();
        //查看类名
        System.out.println(Modifier.toString(object.getClass().getModifiers())+"  "+object.getClass().getName());
        //查看构造的类的结构-->属性结构
        for (Field field : object.getClass().getDeclaredFields()){
            System.out.println(Modifier.toString(field.getModifiers()) + "  "
                    +field.getType()+"  "
                    + field.getName());
        }
        //查看构造的类的结构-->方法结构
        for (Method method : object.getClass().getDeclaredMethods()){
            System.out.println(Modifier.toString(method.getModifiers())+"  "
                    + method.getReturnType()+"  "
                    +method.getName());
        }

        //给对象赋值
        //使用Cglib相关类进行赋值
        BeanMap beanMap = BeanMap.create(object);
        beanMap.put("id", 2);
        beanMap.put("name", "xx");
        //使用JDK反射赋值
        /*Field field = object.getClass().getDeclaredField("$cglib_prop_name");
        field.setAccessible(true);
        field.set(object,"使用反射赋值");*/
        /*Method method = object.getClass().getDeclaredMethod("setName",String.class);
        method.invoke(object,"使用反射赋值");*/

        //以上几种赋值都是可以的,构造出来的类和源码写出来的类不同之处在结果截图里面已经很明显了
        
        //序列化输出
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeValueAsString(object));
    }
}

3.运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值