动态代理的角色及其原理,见下文:
[url]http://tiro-li.iteye.com/blog/1901678[/url]
动态代理的工厂类:DynamicProxyFactory.java
测试类:Test.java
[url]http://tiro-li.iteye.com/blog/1901678[/url]
动态代理的工厂类:DynamicProxyFactory.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxyFactory implements InvocationHandler
{
//被代理的对象
private Object proxyObj;
private DynamicProxyFactory(Object obj)
{
this.proxyObj = obj;
}
//生成动态代理对象的工厂方法
public static Object factory(Object obj)
{
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),new DynamicProxyFactory(obj));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
//使用反射调用被代理对象的方法
return method.invoke(proxyObj,args);
}
}
测试类:Test.java
import java.util.ArrayList;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<String> list = (List<String>)DynamicProxyFactory.factory(new ArrayList<String>());
list.add("hello");
list.add("world");
System.out.println(list);
}
}