Class类
成员方法
public Method getMethod(String name,Class... params);<br /> 返回一个Method对象,仅公共成员方法<br /> public Method getDeclaredMethod(String ,class... params);<br /> 返回一个Method对象,可获取私有成员方法<br /> public Method[] getMethods();<br /> 返回此类所有(不含私有)方法数组
Method类
概述
属于java.base模块下的java.lang.reflect包下的类
成员方法
public String getName(); 获取成员方法名<br /> public Object invoke(Object obj,Object... params); 调用指定方法,obj表示该类的对象,params表示调用该方法所需的参数<br /> public void setAccessible(boolean flag); 是否开启暴力反射(true:开启)
案例
public class ReflectDemo2 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//需求:通过反射获取Student类中的成员方法并调用//1.获取Student类的字节码文件对象Class clazz =Class.forName("Note.Student");//2.获取该类的构造器对象,然后创建Student类的对象Constructor con = clazz.getConstructor();Student stu = (Student) con.newInstance();// System.out.println(stu);//3.获取该类的成员方法对象,然后调用此方法//3.1调用公共的空参方法Method method1 = clazz.getMethod("show1");System.out.println(method1);//打印方法名System.out.println(method1.getName());//调用此方法method1.invoke(stu);//3.2调用一个公共的带参方法Method method2 = clazz.getMethod("show2", int.class);method2.invoke(stu,100);//3.3调用私有的带参方法Method method3= clazz.getDeclaredMethod("show3", int.class, int.class);method3.setAccessible(true);int num = (int) method3.invoke(stu, 10, 20);System.out.println("你录入的两个值的和为:"+num);//3.4获取Student类中的所有的成员方法Method methods[] =clazz.getMethods();for (Method method : methods) {System.out.println(method);}}}
