1.所谓动态代理类是这样一种class,首先它是在运行期生成的,而且在生成的过程当中实现了真实对象实现了的一系列接口,当然它不会帮你做实质性的工作,在生成它的过程当中你必须提供一个实现了InvocationHandler的实例,由它接管实际的工作
2.抽象角色
3.真实角色
4.代理处理器
5.客户端调用
通过这种方式被代理对象可以在运行时动态改变,需要控制的接口也可以动态改变,这样使得程序的灵活性更大
2.抽象角色
package com.lamp.reflect;
public interface IStudentAge {
public void setAge(int age);
}
package com.lamp.reflect;
public interface IStudentName {
public void setName(String name);
}
3.真实角色
package com.lamp.reflect;
public class StudentImpl implements IStudentName,IStudentAge{
String name = null;
int age = 0;
public void setName(String name) {
System.out.println("现在进入真实对象为属性name赋值");
this.name = name;
}
public void setAge(int age) {
System.out.println("现在进入真实对象为属性age赋值");
this.age = age;
}
}
4.代理处理器
package com.lamp.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxy implements InvocationHandler {
//object为真实对象的引用
private Object object = null;
public DynamicProxy(Object object){
this.object = object;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(args != null){
for(Object obj: args){
System.out.println(obj);
}
}
//此时根据参数object调用真实对象方法
method.invoke(object, args);
return null;
}
}
5.客户端调用
package com.lamp.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class ClientTest {
public static void main(String[] args) {
StudentImpl student = new StudentImpl();
InvocationHandler handler = new DynamicProxy(student);
Class<?> clazz = handler.getClass();
//IName指向的是动态生成的代理对象实例,此代理对象实现了你所要被代理对象的所有接口
//这里生成的动态对象也同样实现了StudentImpl所实现的接口
IStudentName IName = (IStudentName)Proxy.newProxyInstance
(clazz.getClassLoader(), student.getClass()
.getInterfaces(), handler);
IName.setName("zhangsan");
System.out.println(IName.getClass());
IStudentAge IAge = (IStudentAge)Proxy.newProxyInstance
(clazz.getClassLoader(), student.getClass()
.getInterfaces(), handler);
IAge.setAge(100);
System.out.println(IAge.getClass());
System.out.println(student.name + ", " + student.age);
}
}
通过这种方式被代理对象可以在运行时动态改变,需要控制的接口也可以动态改变,这样使得程序的灵活性更大