File size: 2,381 Bytes
08aee07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package proxy;

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

public class ProxyTest {
    public static void main(String[] args) {
        //1、创建真实对象
        lenovo lenovo = new lenovo();

        //2、动态代理 增强lenovo对象
        /*
            三个参数:
                1、类加载器 -- 真实对象.getClass().getClassLoader()
                2、接口数组 -- 真实对象..getClass().getInterfaces()
                3、处理器:new InvocationHandler()
         */
        SaleComputer proxy_lenovo = (SaleComputer) Proxy.newProxyInstance(lenovo.getClass().getClassLoader(), lenovo.getClass().getInterfaces(), new InvocationHandler() {
            /*
                代理逻辑编写的方法:代理对象调用的所有方法,都会触发该方法执行
                    参数:
                        1、proxy:代理对象
                        2、method:代理对象调用的方法,所封装的对象
                        3、args:代理对象调用方法时,传递的参数
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("代理方法执行了");
                System.out.println(method.getName());
                System.out.println(Arrays.toString(args));


                //判断是否是sale方法
                if (method.getName().equals("sale")) {

                    //1、增强参数
                    double money = (double) args[0];
                    money = money * 0.85;
                    //使用真实对象调用该方法
                    String obj = (String) method.invoke(lenovo, money);

                    //2、增强方法体
                    System.out.println("送货上门...");

                    //3、增强返回值
                    return obj + "_鼠标垫";

                } else {
                    //使用真实对象调用该方法
                    Object obj = method.invoke(lenovo, args);
                    return obj;
                }
            }
        });

        //2、调用方法
        String computer = proxy_lenovo.sale(8000);
        System.out.println(computer);

        proxy_lenovo.show();
    }
}