CGLIB动态生成一个bean

 

在没有类的情况下,生成一个bean,之前是不敢想象的,现在cglib做到了

import com.alibaba.fastjson.JSON;
import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Bean {
    /**
     * 使用CGLIB的BeanGenerator动态的创建了一个Bean对象,使用addProperty方法可以添加一个属性,在添加属性的同时BeanGenerator会自动生成其Getting、Setting方法。
     *
     * @param args
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        BeanGenerator bean=new BeanGenerator();
        bean.addProperty("name",String.class);
        bean.addProperty("age",Integer.class);
        Object o = bean.create();
        Method m1=o.getClass().getMethod("setName",String.class);
        m1.invoke(o,"www");
        Method m2 = o.getClass().getMethod("getName");
        System.out.println(JSON.toJSONString(o));
        System.out.println(m2.invoke(o));

        BeanMap beanMap = BeanMap.create(o);
        System.out.println(beanMap);
        
    }
}

输出

{"name":"www"}
www
{name=www, age=null}

 

posted @ 2023-03-12 11:15  Mars.wang  阅读(176)  评论(0)    收藏  举报