GCLIB动态代理

1.创建要代理的类

public class Boy {
    public void eat() {
        System.out.println("eat");
    }
}

2.创建拦截器

public class MyMethodInterceptor implements MethodInterceptor {
    @Override
    public 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

你可能感兴趣的:(Java原理知识,java,开发语言)