反射:框架设计的灵魂(2)
-
Class对象功能:
* 获取功能:
1. 获取成员变量们
* Field[] getFields() :获取所有public修饰的成员变量
* Field getField(String name):获取指定名称的 public修饰的成员变量
* Field[] getDeclaredFields():获取所有的成员变量,不考虑修饰符
* Field getDeclaredField(String name)
2. 获取构造方法们
* Constructor<?>[] getConstructors()
* Constructor getConstructor(类<?>… parameterTypes)
* Constructor getDeclaredConstructor(类<?>… parameterTypes)
* Constructor<?>[] getDeclaredConstructors()
3. 获取成员方法们:
* Method[] getMethods()
* Method getMethod(String name, 类<?>… parameterTypes)
* Method[] getDeclaredMethods()
* Method getDeclaredMethod(String name, 类<?>… parameterTypes)
4. 获取全类名
* String getName() -
Field:成员变量
* 操作:
1. 设置值
* void set(Object obj, Object value)
2. 获取值
* get(Object obj)
3. 忽略访问权限修饰符的安全检查
* setAccessible(true):暴力反射 -
Constructor:构造方法
* 创建对象:
* T newInstance(Object… initargs)
* 如果使用空参数构造方法创建对象,操作可以简化:Class对象的newInstance方法 -
Method:方法对象
* 执行方法:
* Object invoke(Object obj, Object… args)
* 获取方法名称:
* String getName:获取方法名