Java中的反射( 三 )

5.反射之操作成员方法(1)Method类概述

反射之操作成员方法的目的:操作Method对象来调用成员方法
Method类概述:每一个成员方法都是一个Method类的对象 。
(2)Class类中与Method相关的方法
* Method getMethod(String name,Class...args);
根据方法名和参数类型获得对应的构造方法对象 , 只能获得public的
* Method getDeclaredMethod(String name,Class...args);
根据方法名和参数类型获得对应的构造方法对象 , 包括public、protected、(默认)、private的
* Method[] getMethods();
获得类中的所有成员方法对象 , 返回数组 , 只能获得public修饰的且包含父类的
* Method[] getDeclaredMethods();
获得类中的所有成员方法对象 , 返回数组,只获得本类的 , 包括public、protected、(默认)、 private的
(3)Method对象常用方法
* Object invoke(Object obj, Object... args)
调用指定对象obj的该方法
args:调用方法时传递的参数
* void setAccessible(true)
设置"暴力访问"——是否取消权限检查 , true取消权限检查 , false表示不取消
示例代码:
public class Demo04 {/*** Method[] getMethods();* 获得类中的所有成员方法对象 , 返回数组 , 只能获得public修饰的且包含父类的* Method[] getDeclaredMethods();* 获得类中的所有成员方法对象 , 返回数组,只获得本类的 , 包含private修饰的*/@Testpublic void test03() {// 获得Class对象Class<Student> c = Student.class;// 获得类中的所有成员方法对象 , 返回数据 , 只能获得public修饰的且包含父类的// Method[] methods = c.getMethods();// 获得类中的所有成员方法对象 , 返回数组,只获得本类的 , 包含private修饰的Method[] methods = c.getDeclaredMethods();for (Method method : methods) {System.out.println(method);}}/*** Method getDeclaredMethod(String name,Class...args);* 根据方法名和参数类型获得对应的构造方法对象 , */@Testpublic void test02() throws Exception {// 获得Class对象Class<Student> c = Student.class;// 根据Class对象创建学生对象Student stu = c.newInstance();// 获得sleep方法对应的Method对象Method m = c.getDeclaredMethod("sleep");// 暴力反射m.setAccessible(true);// 通过m对象执行sleep方法m.invoke(stu);}/*** Method getMethod(String name,Class...args);* 根据方法名和参数类型获得对应的构造方法对象 , */@Testpublic void test01() throws Exception {// 获得Class对象Class<Student> c = Student.class;// 根据Class对象创建学生对象Student stu = c.newInstance();//// 获得study方法对应的Method对象//Method m = c.getMethod("study");//// 通过m对象执行study方法//m.invoke(stu);// 获得study方法对应的Method对象Method m2 = c.getMethod("study", int.class);// 通过m2对象执行study方法m2.invoke(stu, 8);}}6.反射之操作成员变量(1)Field类概述
反射之操作成员变量的目的 :通过Field对象给对应的成员变量赋值和取值
Field类概述: 每一个成员变量都是一个Field类的对象 。
(2)Class类中与Field相关的方法
Field getField(String name);
根据成员变量名获得对应Field对象 , 只能获得public修饰
Field getDeclaredField(String name);
根据成员变量名获得对应Field对象 , 包括public、protected、(默认)、private的
Field[] getFields();
获得所有的成员变量对应的Field对象 , 只能获得public的
Field[] getDeclaredFields();
获得所有的成员变量对应的Field对象 , 包括public、protected、(默认)、private的
(3)Field对象常用方法
void set(Object obj, Object value)
void setInt(Object obj, int i)
void setLong(Object obj, long l)
void setBoolean(Object obj, boolean z)
void setDouble(Object obj, double d)
Object get(Object obj)
int getInt(Object obj)
long getLong(Object obj)
boolean getBoolean(Object ob)
double getDouble(Object obj)
void setAccessible(true); // 暴力反射 , 设置为可以直接访问私有类型的属性 。
Class getType(); // 获取属性的类型 , 返回Class对象 。
setXxx方法都是给对象obj的属性设置使用 , 针对不同的类型选取不同的方法 。
getXxx方法是获取对象obj对应的属性值的 , 针对不同的类型选取不同的方法 。
示例代码:


推荐阅读