1:静态代理 在程序运行前, 它的.class 文件就已经存在了,这种代理类称为静态代理类。
2:动态代理 动态代理类的字节码在程序运行时由Java 反射机制动态生成,无需程序员手工编写它的源代码。
有proxy类和invocationhandler接口来实现其功能.
public static Class<?> getProxyClass(ClassLoader loader, Class<?>[] interfaces)
public static Obj ect newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
InvocationHandler handler) throws IllegalArgumentException
只有通过Proxy 类创建的类才是动态代理类;
每个动态代理类实例都和一个 InvocationHandler 实例关联.
方法会调用与它关联的InvocationHandler 对象的invoke() 方法。
两种实现:通过类构造器来获得对象,一个通过类的静态方法来获取对象.通常用第二种方法.
public class HelloServiceProxyFactory {
/* 创建一个实现了HelloService 接口的动态代理类的实例 参数helloService 引用被代理的HelloService 实例 */
public static HelloService getHelloServiceProxy(final HelloService helloService){
//创建一个实现了InvocationHandler 接口的匿名类的实例
InvocationHandler handler=new InvocationHandler(){
public Object invoke(Obj ect proxy,Method method,Obj ect args[])throws Exception{
System.out.println("before calling "+method); //预处理
Obj ect result=method.invoke(helloService,args);
//调用被代理的HelloService 实例的方法
System.out.println("after calling "+method); //事后处理
return result;
}
};
Class classType=HelloService.class;
return (HelloService)Proxy.newProxyInstance(classType.getClassLoader(),
new Class[]{classType}, handler);
Java 的反射机制在服务器程序和中间件程序中得到了广泛运用。服务器端,往往需要根据客户的请求,动态调用某一个对象的特定方法。
有一种ORM(Object-Relation Mapping,对象-关系映射)中间件能够把任意一个JavaBean 持久化到关系数据库中。