第二步,创建一个InvocationHandler的实现类对象,并将student传入进去,这个student会将生成实现类中的成员变量target进行赋值初始化。
第三步,调用MyProxy中的newInstance方法来获得代理类对象(注意:newInstance 中的参数要是实现类的类类型来获得他的实现Interface接口的类类型,即Person,生成代理类的Java文件就是依据该接口生成的)
1 public static void main(String[] args) {
2 Person student = new Student();
3
4 InvocationHandler h = new Hadler<Person>(student);
5 Person stu = (Person) MyProxy.newInstance(Person.class.getClassLoader(), Student.class.getInterfaces(), h);
6 stu.study2();
7 System.out.println("-------");
8 student.study2();
9 stu.study2(4);
10 stu.study3(4, "A");
11 int a = stu.returnInt(2015);
12 System.out.println(a);
13 }
先吃饭
正在考试中
再睡觉
-------
正在考试中
先吃饭
4
再睡觉
先吃饭
A4
再睡觉
先吃饭
再睡觉
2015