Method类代表某个类中的一个成员方法。
反射通过它可以调用某个类中的一个方法。
package cn.itcast.reflect1;
public class Teacher {
public int age=10;
private String name="Tom";
public void show()
{
System.out.println("name:"+name+" age:"+age);
}
public void show(String msg)
{
System.out.println(msg);
}
public String show(String msg,int i)
{
return msg+" "+i;
}
}
package cn.itcast.reflect1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class Demo1 {
@Test
//得到Teacher类中的show方法的Method对象
public void fun1() throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
//1、得到Class
Class c=Teacher.class;
//2、得到Method
Method m1=c.getDeclaredMethod("show");
Method m2=c.getDeclaredMethod("show", String.class);
//3、让方法执行
Teacher t=(Teacher)c.newInstance();//得到Teacher的对象
m1.invoke(t);//相当于t.show();
m2.invoke(t, "good");//相当于t.show("good")
}
@Test
public void fun2() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException
{
Class c=Teacher.class;
Method m=c.getMethod("show", String.class,int.class);
Object returnValue=m.invoke(c.newInstance(), "Tom",20);//相当于t.show("Tom",20)
//returnValue相当于t.show("Tom",20)的返回值
System.out.println(returnValue);
}
}
1、对于static方法怎么调用呢?
因为static方法是静态方法不需要对象,所以invoke函数的第一个参数写为null。
2、方法的参数如果是数组怎么调用?
在调用invoke时,第二个参数强制转换成Object,或者在外面在包装一层数组。
package cn.itcast.reflect1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class Demo3 {
public static void main(String[] args) {
//要通过反射去调用main方法,并传递参数。
System.out.println(args[0]);
System.out.println(args[1]);
}
@Test
public void fun()throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
//1、得到当前类的Class
Class clazz=Demo3.class;
//2、得到这个类中main方法的Method
Method main=clazz.getMethod("main", String[].class);
//3、调用main方法
//main.invoke(null, new Object[]{new String[]{"hello","world"}});
main.invoke(null, (Object)(new String[]{"hello","world"}));
}
}
invoke(Object 对象,Object….arg);
上面如果写成invoke(null,”hello”,”world”);会将hello,world包装到数组new String[]{“hello”,”world”};这时候arg的值就是一个数组。数组中有两个元素。它认为被调用的方法应该有两个参数。
invoke在将arg传递给args时,就将hello赋值给了args,而world传递给main方法的第二个参数,而main方法没有第二个参数,所以会报参数个数错误。所以第二个参数不能作为数组传递