编写一个实体类:
package com.muou.entity;
public class Student {
public String goHome(){
System.out.println("回家");
return "做作业";
}
}
package com.muou.proxy;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CgLibProxy implements MethodInterceptor{
private Enhancer enhancer = new Enhancer();
public Object getProxy(Class c){
//设置父类
enhancer.setSuperclass(c);
enhancer.setCallback(this);
//创建被代理对象的子类的对象
return enhancer.create();
}
//增强要代理 对象的功能,增加前置和后置处理
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("前置");
//被代理对象方法真正执行的地方
Object result = proxy.invokeSuper(obj, args);
System.out.println("后置");
return result;
}
}
测试方法:
@Test
public void testCglib() {
CgLibProxy cgLibProxy = new CgLibProxy();
Student stu = (Student) cgLibProxy.getProxy(Student.class);
String result = stu.goHome();
System.out.println(result);
}
执行结果:
前置
回家
后置
做作业
当做笔记记录