先看基于jdk实现的动态代理实现例子
1、先声明一个接口类
1 public interface UserService{2 3 public String getName(String msg); 4 }
2、实现上面定义的接口类
1 public class UserServiceImpl implements UserService {2 3 @Override4 public String getName(String msg) {5 System.out.println("###enter getName method###");6 return msg;7 }8 }
3、实现InvocationHandler接口类
1 import java.lang.reflect.Method; 2 import java.lang.reflect.InvocationHandler; 3 4 public class MyInvocationHandler implements InvocationHandler { 5 6 private Object targetObj; 7 8 public MyInvocationHandler(){} 9 10 public MyInvocationHandler(Object obj) {11 12 this.targetObj = obj; 13 }14 15 @Override16 public Object invoke(Object proxy, Method method, Object[] args) 17 throws Throwable {18 19 System.out.println("###enter invoke method pre###");20 Object result = method.invoke(targetObj, args);21 System.out.println("###enter invoke method after###");22 return result;23 }24 }
4、测试类
1 public class JdkProxyMain{ 2 3 public static void main(String[] args) { 4 5 UserService service = new UserServiceImpl(); 6 InvocationHandler invoke = new MyInvocationHandler(); 7 8 UserService proxy = (UserService)Proxy.newProxyInstance(service.getClass().getClassLoader(), service.getClass().getInterfaces(), invoke); 9 proxy.getName();10 }11 }
Cglib动态代理示例(还是基于上面的接口类及实现接口类,cglib也支持类的实现方式来支持动态代理,需引入cglib jar包)
1 public class CglibProxy implements MethodInterceptor {2 3 @Override4 public Object intercept(Object target, Method method, Object[] params, MethodProxy methodProxy) throws Throwable { System.out.println("....enter invoke pre..."); methodProxy.invokeSuper(target, params); System.out.println("...enter invoke end...");5 return null; 6 }7 }
1 public class CglibMain{ 2 3 public static void main(String[] args) { 4 System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "F:\\code");//设置生成代理类的路径 5 CglibProxy cglib = new CglibProxy(); 6 Enhancer enhancer = new Enhancer(); 7 enhancer.setSuperclass(UserServiceImpl.class); 8 enhancer.setCallback(cglib); 9 10 UserService service = (UserService)enhancer.create();11 String result service.getName("cglib");12 }13 14 }