动态代理

2019-05-31  本文已影响0人  万物皆有序和公式

1 jdk代理

package com.example.demo.agent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * @program: demo
 * @description:
 * @author: liuwei
 * @create: 2019-05-31 14:11
 **/
public class LogInvocationHandler implements InvocationHandler {
    public static final String SAY_HI = "sayHi";
    private Hello hello;

    public LogInvocationHandler(Hello hello) {
        this.hello = hello;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName()+"---------");
        Object invokeValue = null;
        if (SAY_HI.equals(method.getName())) {
            System.out.println("==========");
            invokeValue = method.invoke(hello, args);
            System.out.println("*********");
        }
        return invokeValue;
    }

    public static void main(String[] args) {
        Hello hello = (Hello) Proxy.newProxyInstance(LogInvocationHandler.class.getClassLoader(), new Class[]{Hello.class}
                , new LogInvocationHandler(new HelloImpl()));
        hello.sayHi("hi");
        hello.sayBye("bye");
    }
}

2 cjlib代理

package com.example.demo.agent;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: demo
 * @description:
 * @author: liuwei
 * @create: 2019-05-31 16:10
 **/
public class LogMethodInterceptor implements MethodInterceptor {

    public static final String SAY_HI = "sayHi";

    @Override
    public Object intercept(Object o,
                            Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object o1 = null;
        if (method.getName().equals(SAY_HI)) {
            System.out.println("------------");
            o1 = methodProxy.invokeSuper(o, objects);
            System.out.println("============");
        }

        return o1;
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(HelloImpl.class);
        enhancer.setCallback(new LogMethodInterceptor());
        HelloImpl hello = (HelloImpl) enhancer.create();
        hello.sayBye("bye");
        hello.sayHi("hi");
    }
}

pom

<dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
</dependency>
上一篇 下一篇

猜你喜欢

热点阅读