使用cglib在内存中动态生成类

【博文总目录>>>】|【项目源码>>>】

CGLIB是一个强大的、高性能的代码生成库。其被广泛应用于AOP框架(Spring、dynaop)中,用以提供方法拦截操作。本示例展示了如何使用cglib动态生成类。

package wjc.cglib;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

import java.util.Map;

/**
 * 
 * 建立一个动态实体bean,使用cglib动态加入属性,和相应的get,set方法
 * 
* Author: 王俊超 * Date: 2018-02-22 09:18 * Blog: http://blog.csdn.net/derrantcm * Github: https://github.com/wang-jun-chao * All Rights Reserved !!! */
public class CglibBean { /** * 实体Object */ private Object object = null; /** * 属性map */ private BeanMap beanMap = null; public CglibBean() { super(); } public CglibBean(Map> propertyMap) { this.object = generateBean(propertyMap); this.beanMap = BeanMap.create(this.object); } /** * 给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); } /** * 得到该实体bean对象 * * @return */ public Object getObject() { return this.object; } private Object generateBean(Map> propertyMap) { if (propertyMap == null || propertyMap.isEmpty()) { return null; } BeanGenerator generator = new BeanGenerator(); for (Map.Entry> entry : propertyMap.entrySet()) { generator.addProperty(entry.getKey(), entry.getValue()); } return generator.create(); } }
package wjc.cglib;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * CGLIB是一个强大的、高性能的代码生成库。其被广泛应用于AOP框架(Spring、dynaop)中,用以提供方法拦截操作。
 * 
* Author: 王俊超 * Date: 2018-02-22 09:26 * Blog: http://blog.csdn.net/derrantcm * Github: https://github.com/wang-jun-chao * All Rights Reserved !!! */
public class ClassGeneration { public static void main(String[] args) throws ClassNotFoundException { // 设置类成员属性 Map> propertyMap = new HashMap<>(); propertyMap.put("id", Class.forName("java.lang.Integer")); propertyMap.put("name", Class.forName("java.lang.String")); propertyMap.put("address", Class.forName("java.lang.String")); // 生成动态 Bean CglibBean bean = new CglibBean(propertyMap); // 给 Bean 设置值 bean.setValue("id", 123); bean.setValue("name", "454"); bean.setValue("address", "789"); // 从 Bean 中获取值,当然了获得值的类型是 Object System.out.println("id = " + bean.getValue("id")); System.out.println("name = " + bean.getValue("name")); System.out.println("address = " + bean.getValue("address")); // 获得bean的实体 Object object = bean.getObject(); Class clazz = object.getClass(); // 查看生成的类名 System.out.println(clazz.getName()); // 通过反射查看所有方法名 Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { System.out.println(method.getName()); } } }

运行结果
这里写图片描述

你可能感兴趣的:(JAVA)