- package cn.javastudy.p16.proxy.demo;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.ArrayList;
- import java.util.Collection;
- public class ProxyDemo {
- /**
- * @param args
- * @throws NoSuchMethodException
- * @throws SecurityException
- * @throws InvocationTargetException
- * @throws IllegalAccessException
- * @throws InstantiationException
- * @throws IllegalArgumentException
- */
- public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
- // TODO Auto-generated method stub
- Class<?> clazzProxy=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
- /*Method[] m=clazzProxy.getMethods();
- for(Method mm:m)
- System.out.println(mm.toString());*/
- Constructor<?> constructor=clazzProxy.getConstructor(InvocationHandler.class);
- //第一种方法
- /*class MyInvocationHandler implements InvocationHandler
- {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- ArrayList<?> list=new ArrayList<Object>();
- Object o = method.invoke(list, args);
- return o;
- }
-
- }
- MyInvocationHandler handler=new MyInvocationHandler();
- Collection<String> c=(Collection<String>)constructor.newInstance(new MyInvocationHandler());*/
- //第二种方法
- /*Collection c=(Collection)constructor.newInstance(new InvocationHandler(){
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- ArrayList<?> list=new ArrayList<Object>();
- Object o = method.invoke(list, args);
- return o;
- }});
-
- c.add("a");
- c.add("b");
- c.add("c");
- c.add("d");*/
- //第三种方法
- Collection c=(Collection)Proxy.newProxyInstance(
- Collection.class.getClassLoader(),
- new Class[]{Collection.class},
- new InvocationHandler(){
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- ArrayList<?> list=new ArrayList<Object>();Thread a=null;a.start();
- Object o = method.invoke(list, args);
- return o;
- }} );
- c.add("a");
- c.add("b");
- c.add("c");
- c.add("d");
- }
-
- }
复制代码 动态代理的应用,Proxy的newProxyInstance的原理:
此方法接收三个参数,第一个参数为被代理的类的类加载器,第二个为被代理的类实现的接口的字节码数列表(字节码数组),第三个为InvocationHandler的实现类.
通过调用调用这方不就可以产生一个代理对象,这个代里对像实现了被代理类的所有接口.
当调用这个代里对象时,就会调用InvocaionHandler中的Invoke方法,然后再通过个方法根据目标对象调用被代理的相应方法.返回来的值再传递给代理相应方法. |