注意:获取成员方法与前面的有无declare概念不同
-
方法
1.Method[] getMethods 返回一个包含 方法对象的数组 ,这里的方法,是该类或接口的所有公共方法,也包括继承的方法
2.Method[] getDeclareMethods 返回本类的方法,不包括继承的 -
代码
//获取Class对象
Class<?> c = Class.forName("com.itheima_02.Student");
//Method[] getMethods() 返回一个包含 方法对象的数组, 方法对象反映由该 Class对象表示的类或接口的所有公共方法,包括由类或接口声明的对象以及从超类和超级接口继承的类
//Method[] getDeclaredMethods() 返回一个包含 方法对象的数组, 方法对象反映由 Class对象表示的类或接口的所有声明方法,包括public,protected,default(package)访问和私有方法,但不包括继承方法
// Method[] methods = c.getMethods();
Method[] methods = c.getDeclaredMethods();
for(Method method : methods) {
System.out.println(method);
}
System.out.println("--------");
//Method getMethod(String name, Class<?>... parameterTypes) 返回一个 方法对象,该对象反映由该 Class对象表示的类或接口的指定公共成员方法
//Method getDeclaredMethod(String name, Class<?>... parameterTypes) 返回一个 方法对象,它反映此表示的类或接口的指定声明的方法 Class对象
//public void method1()
Method m = c.getMethod("method1");
//获取无参构造方法创建对象
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
// obj.m();
//在类或接口上提供有关单一方法的信息和访问权限
//Object invoke(Object obj, Object... args) 在具有指定参数的指定对象上调用此 方法对象表示的基础方法
//Object:返回值类型
//obj:调用方法的对象
//args:方法需要的参数
m.invoke(obj);
// Student s = new Student();
// s.method1();
- 示例
/*
练习:通过反射实现如下操作
Student s = new Student();
s.method1();
s.method2("林青霞");
String ss = s.method3("林青霞",30);
System.out.println(ss);
s.function();
*/
Class<?> c = Class.forName("com.itheima_02.Student");
//Student s = new Student();
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
//s.method1();
Method m1 = c.getMethod("method1");
m1.invoke(obj);
//s.method2("林青霞");
Method m2 = c.getMethod("method2", String.class);
m2.invoke(obj,"林青霞");
// String ss = s.method3("林青霞",30);
// System.out.println(ss);
Method m3 = c.getMethod("method3", String.class, int.class);
Object o = m3.invoke(obj, "林青霞", 30);
System.out.println(o);
//s.function();
// Method m4 = c.getMethod("function"); //NoSuchMethodException: com.itheima_02.Student.function()
Method m4 = c.getDeclaredMethod("function");
m4.setAccessible(true);
m4.invoke(obj);