江西广告网

标题: RTTI Reflection总结 [打印本页]

作者: 云海顽石    时间: 2009-2-12 09:00
标题: RTTI Reflection总结
package com.cxz.thinking.act10; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Random; class method{ public int sum (Integer a, Integer b){ return a b; } public int minus(Integer a, Integer b){ return a - b; } public int plusplus(Integer a){ return a; } public double show(Double dbl){ return dbl 100; } } package com.cxz.thinking.act10; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Random; class method{ public int sum (Integer a, Integer b){ return a b; } public int minus(Integer a, Integer b){ return a - b; } public int plusplus(Integer a){ return a; } public double show(Double dbl){ return dbl 100; } } [1] [2] package com.cxz.thinking.act10; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Random; class method{ public int sum (Integer a, Integer b){ return a b; } public int minus(Integer a, Integer b){ return a - b; } public int plusplus(Integer a){ return a; } public double show(Double dbl){ return dbl 100; } } Java代码 public class DynamicInvoke { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, IllegalArgumentException { Class myCls = Class.forName("com.cxz.thinking.act10.method");//动态加载 Object obj = myCls.newInstance();//创建一个method对象Method.invoke()的第一个参数需要 Method[] methods = myCls.getDeclaredMethods();//得到全体方法数组 for( int i = 0; i < methods.length; i ){ Class[] paramType = methods.getParameterTypes();//get the type of each param Object[] paramValue = new Object[paramType.length];//set the values在下文写如数据 Random rand = new Random(); for(int j = 0; j < paramType.length; j ){ if(paramType[j] == Integer.class){//本程序的参数仅仅限与Integer,和Double类 paramValue[j] = rand.nextInt();//动态生成10以下 } else if(paramType[j] == Double.class){ paramValue[j] = rand.nextDouble();//动态生成控制在10以下 } } String params = ""; for(int k = 0; k < paramType.length; k ){ params = paramValue[k].toString() ","; } params = params.substring(0, params.length() - 1); params = "[ " params " ]"; System.out.println("{" methods.toString() "}" params methods.invoke(obj, paramValue));//开始调用invoke调用 } } 上一页 [1] [2]




欢迎光临 江西广告网 (http://bbs.jxadw.com/) Powered by Discuz! X3.2