首页 > 代码库 > 动态代理

动态代理

 

public interface HelloWorld
{

void sayHello(String name);

}

public HelloWorldImpl implements HelloWorld
{

@Override
public void sayHello(String name)
{
System.out.println("Hello " + name);
}

}

实现java的动态代理接口

public class CustomInvocationHandler implements InvocationHandler
{

private Object target;

public CustomInvocationHandler(Object target)
{

this.target = target;

}

@Override
public Object invoke(Object proxy,Method method,Object[] args)throw Throwable
{

Object retVal = method.invoke(target,args);

return retVal;

}

}


使用代理类

public class ProxyTest
{

public static void main(String[] args) throws Exception
{

InvocationHandler handler = new CustomInvocationHandler(new HelloWorldImpl());

HelloWorld proxy = (HelloWorld)Proxy.newProxyInstance(
ProxyTest.class.getClassLoder(),new Class[]{HelloWorld.class},handler);
proxy.sayHello("你好");
)

}

}
=====================================
public class Proxy
{

private static Map loaderToCache = new WeakHashMap();

private static Object pendingGenerationMarke = new Object();

private static Map proxyClass Collections.synchronizedMap(new WeakHashMap());

protected InvocationHandler h;

protected Proxy(InvocationHandler h)
{
this.h = h;
}

private Proxy(){}

public static Object newProxyInstance(ClassLoader loader,class<?> [] interface,InvocationHandler h)
{

if(h == null)
{
throw new NullPointerException();
}

Class cl = getProxyClass(loader,interface);

Constructor cons = cl.getConstructor(constructorParams); //constructorParams這個怎麽來的
cons.newInstance(new Object[]{h});

}

public getProxyClass



}

 

======================================动态代理总结================================

1 通过实现InvocationHandler接口创建自己的调用处理器

InvocationHandler handler = new InvocationHandlerImpl(...)

2 通过为Proxy类指定ClassLoader对象和一组interface创建动态代理类

Proxy.getProxyClass(classLoader,new Class[]{...});

3 通过反射机制获取动态代理类的构造函数,其参数类型是调用处理器接口类型

Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.Class});

4 通过构造函数创建代理类实例,此时需要将调用处理器对象作为参数传入

Interfae Proxy = constructor.newInstance(new Object[](handler));

为了简化对象创建过程,Proxy类中的newInstance方法封装了2-4,只需要两步即可完成代理对象的创建

生成的ProxySubject 继承 Proxy 类 实现 Subject接口,实现的Subject的方法实际调用处理器的invoke方法

而invoke方法利用反射调用的是被代理对象的方法

(Object)method.invoke(proxied,args)

动态代理