通过反射来调用类的方法,本质上还是类的实例进行调用,只是利用反射机制实现了方法的调用
Student类
class Student{
private String name;
public Student(String name) {
= name;
}
public void test(String str) {
(name+()+"的test()被调用");
}
}
调用`getMethod()`方法,我们可以获取到类中所有声明为public的方法,得到一个Method对象,我们可以通过Method对象的`invoke()`方法(返回值就是方法的返回值,因为这里是void,返回值为null)来调用已经获取到的方法,注意传参。
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<Student> clazz = ;
Student student = ().newInstance("zzp");
//通过方法名和形参类型获取类中的方法
Method method = ("test", );
(student, "zp");
}
当出现非public方法时,我们可以通过反射来无视权限修饰符,获取非public方法并调用
(true);
Method和Constructor都和Class一样,他们存储了方法的信息,包括方法的形式参数列表,返回值,方法的名称等内容,我们可以直接通过Method对象来获取这些信息
public static void main(String[] args) throws ReflectiveOperationException {
Class<?> clazz = ("Student");
Method method = ("test", ); //通过方法名和形参类型获取类中的方法
(()); //获取方法名称
(()); //获取返回值类型
}