使用cglib动态为Java类添加方法

本文通过一个具体的示例展示了如何使用CGLib库在Java中创建动态代理,包括定义接口、实现类及增强器的过程,并实现了日期格式转换的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CGLib(Code Generation Library)是一个强大的,高性能,高质量的字节码操作类库,它可以在运行期扩展Java类与实现Java接口,Spring、Hibernate等很多著名的框架都使用了它。
[url=https://github.com/cglib/cglib/]https://github.com/cglib/cglib/[/url]

其他的库还有:
[url=http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/]Javassist (Java Programming Assistant)[/url]、[url=http://asm.ow2.org/]ASM[/url]、[url=http://commons.apache.org/proper/commons-bcel/]Apache Commons BCEL(Byte Code Engineering Library)[/url]


public class CGLibExample {

@SuppressWarnings("unchecked")
public static void main(String[] args) {

// 定义一个参数是字符串类型的setCreatedAt方法
InterfaceMaker im = new InterfaceMaker();
im.add(new Signature("setCreatedAt", Type.VOID_TYPE,
new Type[] { Type.getType(String.class) }), null);

Class myInterface = im.create();

Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(ExampleBean.class);
enhancer.setInterfaces(new Class[] { myInterface });
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {

ExampleBean bean = (ExampleBean) obj;

// 调用字符串类型的setCreatedAt方法时,转换成Date型后调用Setter
if (method.getName().startsWith("setCreatedAt")
&& args[0] != null && args[0] instanceof String) {

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = null;
try {
date = sdf.parse((String) args[0]);
} catch (final Exception e) { /* nop */ }
bean.setCreatedAt(date);
return null;

}
return proxy.invokeSuper(obj, args);
}
});

// 生成一个Bean
ExampleBean bean = (ExampleBean) enhancer.create();
bean.setId(999);

try {
Method method = bean.getClass().getMethod("setCreatedAt", new Class[] {String.class});
method.invoke(bean, new Object[]{"20100531"});
} catch (final Exception e) {
e.printStackTrace();
}

System.out.printf("id : [%d] createdAt : [%s]\n", bean.getId(), bean.getCreatedAt());
}
}

class ExampleBean implements Serializable {
private static final long serialVersionUID = -8121418052209958014L;

private int id;
private Date createdAt;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public Date getCreatedAt() {
return createdAt;
}

public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}


[b]运行结果:[/b]

[quote]id : [999] createdAt : [Mon May 31 00:00:00 CST 2010][/quote]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值