十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
Java 创建动态类和查看方法列表信息的实例
成都创新互联公司于2013年创立,先为襄阳等服务建站,襄阳等地企业,进行企业商务咨询服务。为襄阳企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。Sample code :
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; public class ProxyTest { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class); System.out.println(clazzProxy); System.out.println("------constructor method list ------"); Constructor[] constructors = clazzProxy.getConstructors(); for(Constructor constructor:constructors){ StringBuilder sb = new StringBuilder(constructor.getName()); sb.append("("); Type[] parameterTypes = constructor.getParameterTypes(); for(Type parameterType:parameterTypes){ sb.append(parameterType.toString()+","); } if(parameterTypes.length>0){ sb.deleteCharAt(sb.length()-1); } sb.append(")"); System.out.println(sb.toString()); } System.out.println("------constructor method list ------\n\n"); System.out.println("------ method list ------"); Method[] methods = clazzProxy.getMethods(); for(Method method:methods){ StringBuilder sb2 = new StringBuilder(method.getName()); sb2.append("("); Type[] parameterTypes = method.getParameterTypes(); for(Type parameterType:parameterTypes){ sb2.append(parameterType.toString()+","); } if(parameterTypes.length>0){ sb2.deleteCharAt(sb2.length()-1); } sb2.append(")"); System.out.println(sb2.toString()); } System.out.println("------ method list ------"); Constructor proxyConstructor = clazzProxy.getConstructor(InvocationHandler.class); class MyInvocationHandler implements InvocationHandler{ ArrayList target = new ArrayList(); public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object obj = method.invoke(target, args); return obj; } } MyInvocationHandler mih = new MyInvocationHandler(); Collection collectionProxy = (Collection) proxyConstructor.newInstance(mih); collectionProxy.add("zhuang"); collectionProxy.add("alex"); System.out.println("collectionProxy size:"+collectionProxy.size()); Collection collectionProxy2 = (Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(),new Class[] {Collection.class},new InvocationHandler(){ ArrayList target = new ArrayList(); public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object obj = method.invoke(target, args); return obj; } }); collectionProxy2.add("one"); collectionProxy2.add("two"); collectionProxy2.add("three"); System.out.println("collectionProxy2 size:"+collectionProxy2.size()); }