java CGLIB 动态代理示例

版权声明:转载请注明来源 https://blog.csdn.net/genghaihua/article/details/89386633
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

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


interface Hello {
    String sayHello(String str);
}

// 实现
class HelloImp implements Hello {
    @Override
    public String sayHello(String str) {
        return "HelloImp: " + str;
    }
}

class LogInvocationHandler implements InvocationHandler {
    private Object target;

    public Object getProxyInstance(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if ("sayHello".equals(method.getName())) {
            System.out.println("You said: " + Arrays.toString(args));
        }
        return method.invoke(target, args);
    }
}
class CglibProxy implements MethodInterceptor {
    private Object target;

    public Object getProxyInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);  // call back method
        return enhancer.create();  // create proxy instance
    }
    @Override
    public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("before target method...");
        Object result = methodProxy.invokeSuper(target, args);
        System.out.println("after target method...");
        return result;
    }
}
public class Test1 {
    public static void main(String[] args) {
        CglibProxy proxy = new CglibProxy();
        Hello hello = (Hello) proxy.getProxyInstance(new HelloImp());
        System.out.println(hello.sayHello("Leon"));
    }
}

pom

<dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.1</version>
        </dependency>

猜你喜欢

转载自blog.csdn.net/genghaihua/article/details/89386633