package com.itcast.day3; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collection; public class ProxyTest { public static void main(String[] args)throws Exception { Class clazzProxy1=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class); System.out.println(clazzProxy1.getName());//com.sun.proxy.$Proxy0 /****打印动态生成的代理类的构造器列表*****/ /** * $Proxy0() * $Proxy0(InvoketionHandler) */ System.out.println("--------begin constructors list----------"); Constructor[] constructors=clazzProxy1.getConstructors(); for(Constructor constructor:constructors){ String name=constructor.getName(); StringBuilder sb=new StringBuilder(name); sb.append("("); Class[] clazzParams=constructor.getParameterTypes(); for(Class clazz:clazzParams){ sb.append(clazz.getName()); sb.append(','); } if(clazzParams!=null&&clazzParams.length!=0) sb.deleteCharAt(sb.length()-1); sb.append(")"); System.out.println(sb); } /**只有一个有参数的构造器 --------begin constructors list---------- com.sun.proxy.$Proxy0(java.lang.reflect.InvocationHandler) */ /****打印动态生成的代理类的方法列表*****/ System.out.println("--------begin methods list----------"); Method[] methods=clazzProxy1.getMethods(); for(Method method:methods){ String name=method.getName(); StringBuilder sb=new StringBuilder(name); sb.append("("); Class[] clazzParams=method.getParameterTypes(); for(Class clazz:clazzParams){ sb.append(clazz.getName()); sb.append(','); } if(clazzParams!=null&&clazzParams.length!=0) sb.deleteCharAt(sb.length()-1); sb.append(")"); System.out.println(sb); } /** * 都是Collection和Object里的方法 * --------begin methods list---------- add(java.lang.Object) equals(java.lang.Object) 这三个派发给InvocationHandler,而其他方法如getClass()由Proxy自己实现 toString() hashCode() clear() contains(java.lang.Object) isEmpty() addAll(java.util.Collection) iterator() size() toArray([Ljava.lang.Object;) toArray() remove(java.lang.Object) containsAll(java.util.Collection) removeAll(java.util.Collection) retainAll(java.util.Collection) isProxyClass(java.lang.Class) getProxyClass(java.lang.ClassLoader,[Ljava.lang.Class;) getInvocationHandler(java.lang.Object) newProxyInstance(java.lang.ClassLoader,[Ljava.lang.Class;,java.lang.reflect.InvocationHandler) wait(long) wait() wait(long,int) getClass() notify() notifyAll() */ } }