需求:通过该方法运行任意类的任意有参数与无参数的方法
public class Test1 {
public static void main(String[] args) {
try {
Class<?> c=Class.forName("testRef.Test2");
Method[] methods=c.getDeclaredMethods();
for(int i=0;i<methods.length;i++) {
Method method=methods[i];
if(method.getGenericParameterTypes().length!=0) {
@SuppressWarnings("rawtypes")
Class[]types=method.getParameterTypes();
for(int j=0;j<types.length;j++) {
System.out.println(types[j]);
}
Object obj=c.getConstructor(new Class[]{}).newInstance(new Object[] {});
//以下这行为异常代码 即Test1.java:26
method.invoke(obj, method.getParameterTypes());
}else {
Object obj=c.getConstructor(new Class[]{}).newInstance(new Object[] {});
method.invoke(obj, new Class[] {});
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}