超简单的java动态代理

 

 

public static void main(String[] args) {
        CustomerSImpl c = new CustomerSImpl();
        // java reflect 包提供的动态代理
        CustomerSer jdkProxy = (CustomerSer) Proxy.newProxyInstance(CustomerSImpl.class.getClassLoader(), CustomerSImpl.class.getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("对世界");
                Object result = method.invoke(c,args);
                System.out.println("from jdk");
                return result;
            }
        });
        jdkProxy.sayHello();
        System.out.println("---------------------------------");
        // 三方包cglib提供的动态代理
        CustomerSImpl cglibProxy = (CustomerSImpl) Enhancer.create(c.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("对世界");
                Object result = method.invoke(c,args);
                System.out.println("from cglib");
                return result;
            }
        });
        cglibProxy.sayHello();
    }

 

posted @ 2022-03-11 17:24  田海超  阅读(42)  评论(0编辑  收藏  举报