1、被代理的类: Target.java
- public class Target {
- public String execute() {
- String message = "Target class";
- System.out.println(message);
- return message;
- }
- }
2、代理类:MyMethodInterceptor.java
- import net.sf.cglib.proxy.MethodInterceptor;
- import net.sf.cglib.proxy.MethodProxy;
- import java.lang.reflect.Method;
- public class MyMethodInterceptor implements MethodInterceptor {
- public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
- System.out.println("++Target start++");
- Object result = methodProxy.invokeSuper(object,args);
- System.out.println("++Target end++");
- return "hello";
- }
- }
3、测试类:TestCglibProxy.java
- import net.sf.cglib.proxy.Enhancer;
- public class TestCglibProxy {
- public Object createProxy(Class targetClass) {
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(targetClass);
- enhancer.setCallback(new MyMethodInterceptor());
- return enhancer.create();
- }
- public static void main(String rags[]) {
- //Target target = new Target();
- TestCglibProxy test = new TestCglibProxy();
- Target proxyTarget = (Target) test.createProxy(Target.class);
- String res = proxyTarget.execute();
- System.out.println(res);
- }
- }
4、执行结果
- ++Target start++
- Target class
- ++Target end++
- hello
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/426494,如需转载请自行联系原作者