1.创建要代理的类
public class Boy {public void eat() {System.out.println("eat");}
}
2.创建拦截器
public class MyMethodInterceptor implements MethodInterceptor {@Overridepublic Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {System.out.println("chief cooking");methodProxy.invokeSuper(o,objects);return null;}
}
3.通过 Enhancer 类的 create()创建代理类
public class CglibProxyFactory {public static Object getProxy(Class<?> clazz) {// 创建动态代理增强类Enhancer enhancer = new Enhancer();// 设置类加载器enhancer.setClassLoader(clazz.getClassLoader());// 设置被代理类enhancer.setSuperclass(clazz);// 设置方法拦截器enhancer.setCallback(new MyMethodInterceptor());// 创建代理类return enhancer.create();}
}
4.运行
public class GCLIB {public static void main(String[] args) {Boy boy = (Boy) CglibProxyFactory.getProxy(Boy.class);boy.eat();}
}
5.运行成功
chief cooking
eat进程已结束,退出代码0