<span style="white-space:pre"> </span>public void fun(){
System.out.println("fun1");
}
public void fun(String name,int password){
System.out.println(name+"::"+password);
}
public Class[] fun(String name,int[] password){
return new Class[]{String.class};
}
private void fun(InputStream in){
System.out.println(in);
}
public static void fun(int num){
System.out.println(num);
}
对应如下
<span style="white-space:pre"> </span>public void test1() throws Exception{
Person p = new Person();
Class clazz = Class.forName("reflect.Person");
//fun为调用的函数
Method method = clazz.getMethod("fun", null);
//p为对象,后面为参数
method.invoke(p, null);
}
public void test2() throws Exception{
Person p = new Person();
Class clazz = Class.forName("reflect.Person");
Method method = clazz.getMethod("fun",String.class,int.class);
method.invoke(p,"xiaoming",22);
}
public void test3() throws Exception{
Person p = new Person();
Class clazz = Class.forName("reflect.Person");
Method method = clazz.getMethod("fun", String.class,int[].class);
Class cs[] = (Class[]) method.invoke(p, "zhangsan",new int[]{1,2,3});
System.out.println(cs[0]);
}
public void test4() throws Exception{
Person p = new Person();
Class clazz = Class.forName("reflect.Person");
Method method = clazz.getDeclaredMethod("fun",InputStream.class);//private型的
method.setAccessible(true);
method.invoke(p,new FileInputStream("d:\\test.txt"));//此文件要存在
}
public void test5() throws Exception{
Person p = new Person();
Class clazz = Class.forName("reflect.Person");
Method method = clazz.getMethod("fun", int.class);
//静态方法不需要对象也行
method.invoke(null,23);
}