动态代理

1、代理

以通俗方式理解

目标对象/被代理对象------房主:真正的租房方法

代理对象--------中介:有租房子的方法

执行代理对象方法的对象------租房的人

2、动态代理

不用手动编写一个代理对象,不需要编写与目标对象相同的方法,运行时在内存中动态生成代理对象。

生成动态代理的方法:

static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

1 package com.alphajuns.proxy;
2 
3 public interface TargetInterface {
4     
5     public abstract void method1();
6     public abstract String method2();
7     public abstract int method3(int x);
8     
9 }
 1 package com.alphajuns.proxy;
 2 
 3 public class Target implements TargetInterface {
 4 
 5     @Override
 6     public void method1() {
 7         System.out.println("method1 running ...");
 8     }
 9 
10     @Override
11     public String method2() {
12         System.out.println("method2 running ...");
13         return "method2";
14     }
15 
16     @Override
17     public int method3(int x) {
18         System.out.println("method3 running ...");
19         return x;
20     }
21 
22 }
 1 package com.alphajuns.proxy;
 2 
 3 import java.lang.reflect.InvocationHandler;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Proxy;
 6 
 7 import org.junit.Test;
 8 
 9 public class ProxyTest {
10     
11     @Test
12     public void test() {
13         // 获得动态代理对象,在程序运行时,在内存中动态的为Target创建一个虚拟的代理对象
14         TargetInterface objProxy = (TargetInterface) Proxy.newProxyInstance(
15                 Target.class.getClassLoader(), 
16                 new Class[]{TargetInterface.class}, 
17                 new InvocationHandler() {
18                     // invoke执行代理对象的方法
19                     // method代表目标对象的方法字节码对象
20                     // args代表目标对象相应的方法参数
21                     @Override
22                     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
23                         System.out.println("目标对象方法前的逻辑");
24                         // 执行目标对象的方法
25                         Object invoke = method.invoke(new Target(), args);
26                         System.out.println("目标对象方法后的逻辑");
27                         return invoke;
28                     }
29                 }
30                 );
31         
32         objProxy.method1();
33         String method2 = objProxy.method2();
34         System.out.println(method2);
35     }
36 }
原文地址:https://www.cnblogs.com/alphajuns/p/9980338.html