public class DynamicInvoker {
public static void main(String[] args) {
// TODO Auto-generated method stub
DynamicInvoker app=new DynamicInvoker();
app.sayHello("张三", 2);
try {
try {
app.getClass().getMethod("sayHello", new Class[] {Class.forName("java.lang.String") ,Integer.TYPE})
.invoke(app, "bb",2);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
app.getClass().getMethod("sayHello", String.class ,int.class )
.invoke(app, new Object[] {"李四",3});
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sayHello(String name,int numberOfTimes)
{
for (int i = 0; i < numberOfTimes; i++) {
System.out.println("hello:"+name);
}
}
}
通过提示我们可以看到,Integer.TYPE实际上就是代表int的类型
所以结果是一样的。