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; } }
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[i].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;//动态生成10以下 } else if(paramType[j] == Double.class){ paramValue[j] = rand.nextDouble()%10;//动态生成控制在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[i].toString() + "}"+params+ methods[i].invoke(obj, paramValue));//开始调用invoke调用 } }