通过反射获得其他类中对象,并调用对象方法
Handler handler=(Handler) ReflectionUtil.getMethodResult(className, "getHandler");
handler.sendMessage(msg);
//获得其他类中的 handler 并发送消息
/*原写法:YourActivity.getHandler().sendMessage(msg);*/
Map<String,Integer> fragmentHeightCache=(Map<String,Integer>) ReflectionUtil.getMethodResult(className, "getFragmentHeightCache");
fragmentHeightCache.put(fragmentName, 300);
/*原写法YourActivity.fragmentHeightCache.put(fragmentName, 300);
YourActivity 需要:
1. 声明成员变量: handler 与 fragmentHeightCache;
public static Map<String,Integer> fragmentHeightCache=new HashMap<String,Integer>();
public static Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
setFragmentLayoutHeight((int) msg.obj);
Log.e("TAG case1", "params.height"+msg.obj);
break;
}
}
};
public static Handler getHandler(){
return mHandler;
}
public static Map<String,Integer> getFragmentHeightCache(){
return fragmentHeightCache;
}
2.定义set get 方法
public static Handler getHandler(){
return mHandler;
}
public static Map<String,Integer> getFragmentHeightCache(){
return fragmentHeightCache;
}
可以看到:
ReflectionUtil.getMethodResult(className,"YourFunctionName");
此函数,是通过 className(全路径,可用 this.getClass().getName()
获得) 与 YourFunctionName 经过反射获得到 目标类 中的对象.然后强转型后使用对象.
类代码如下:
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object getMethodResult(String className ,String MethodName){
try {
Class clazz=Class.forName(className);
//反射获得类
Object obj = clazz.getConstructor().newInstance();
//通过构造函数构造出该类的实体
//Method[] methodArray = clazz.getDeclaredMethods();
//获得所有方法(公私有方法都会有,遍历可获得所有方法,功能自行想象)
Method m = clazz.getDeclaredMethod(MethodName, null);
//根据方法名以及返回参数获得方法的实体.(第一个参数是方法名,第二个参数是方法的入参)
m.setAccessible(true);//解除私有限定
Object result = m.invoke(obj, null);
//需要两个参数,一个是要调用的对象(获取有反射),一个是实参
System.out.println("返回值:" + result);
return result;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
使用方法:
1. 在目标类中 创建变量, 并写出变量的 set get 方法.
2. 创建个 Util 类 粘过去 上面的 getMethodResult 方法
3. 调用 目标变量类型 变量名=(目标变量类型) ReflectionUtil.getMethodResult(目标类全路径, "目标变量 get 方法名");
获得目标类中目标成员变量
4. 拿到目标变量后,即可正常操作