java动态代理DynamicProxy
1.被代理对象的接口:
1 package test.dynamicproxy;
2
3 public interface TargetInterface {
4 public void SayHello();
5 public int sum(int a ,int b);
6 }
2.被代理的对象:
01 package test.dynamicproxy;
02
03 public class Target implements TargetInterface {
04
05 public void SayHello(){
06 System.out.println(“Hello”);
07 }
08 public int sum(int a, int b) {
09 return a+b;
10 }
11 }
3.InvocationHandler包装:
01 package test.dynamicproxy;
02
03 import java.lang.reflect.InvocationHandler;
04 import java.lang.reflect.Method;
05
06 public class TargetInvocationHandler implements InvocationHandler {
07
08 private Object object;
09 public TargetInvocationHandler(Object obj){
10 this.object=obj;
11 }
12
13 public Object invoke(Object proxy, Method method, Object[] args2)
14 throws Throwable
15 {
16 doBefore();
17 Object result = method.invoke(object, args2);
18 doAfter();
19 return result;
20 }
21