依旧先贴出Student类
public class Student { //私有的,无参无返回值 private void show() { System.out.println("私有的show方法,无参无返回值"); } //公共的,无参无返回值 public void function1() { System.out.println("function1方法,无参无返回值"); } //公共的,有参无返回值 public void function2(String name) { System.out.println("function2方法,有参无返回值,参数为" + name); } //公共的,无参有返回值 public String function3() { System.out.println("function3方法,无参有返回值"); return "aaa"; } //公共的,有参有返回值 public String function4(String name) { System.out.println("function4方法,有参有返回值,参数为" + name); return "aaa"; } }
使用以上图中四种方法获取到方法
import java.lang.reflect.Method; public class myfl1 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // mothed1(); // nothed2(); // mothed3(); //获取私有成员方法 Class clazz = Class.forName("com.kerwin.myflect1.myflect12.Student"); Method show = clazz.getDeclaredMethod("show"); System.out.println(show); } private static void mothed3() throws ClassNotFoundException, NoSuchMethodException { /*//获取无参无返回值的公共构造方法 Class clazz = Class.forName("com.kerwin.myflect1.myflect12.Student"); //这里如果有参数的话是需要在function1后加上参数 Method method = clazz.getMethod("function1"); System.out.println(method);*/ //获取有形参的 Class clazz = Class.forName("com.kerwin.myflect1.myflect12.Student"); Method method = clazz.getMethod("function2",String.class); System.out.println(method); } private static void nothed2() throws ClassNotFoundException { //返回所有成员方法对象的数组 不包括继承的 Class clazz = Class.forName("com.kerwin.myflect1.myflect12.Student"); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { System.out.println(method); } } private static void mothed1() throws ClassNotFoundException { //返回所有成员方法对象的数组 包括继承的 Class clazz = Class.forName("com.kerwin.myflect1.myflect12.Student"); Method[] methods = clazz.getMethods(); for (Method method : methods) { System.out.println(method); } } }
运行成员方法
这里还是复用下某机构的代码
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 获取Method对象并运行 */ public class ReflectDemo2 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { // Object invoke(Object obj, Object... args):运行方法 // 参数一:用obj对象调用该方法 // 参数二:调用方法的传递的参数(如果没有就不写) // 返回值:方法的返回值(如果没有就不写) //1.获取class对象 Class clazz = Class.forName("com.itheima.myreflect5.Student"); //2.获取里面的Method对象 function4 Method method = clazz.getMethod("function4", String.class); //3.运行function4方法就可以了 //3.1创建一个Student对象,当做方法的调用者 Student student = (Student) clazz.newInstance(); //3.2运行方法 Object result = method.invoke(student, "zhangsan"); //4.打印一下返回值 System.out.println(result); } }