反射获取变量、反射调用函数方法(java、安卓)

本文详细介绍了一种利用反射机制获取对象内部变量及调用方法的技术。反射是Java中的高级特性,可以实现在运行时检查类的信息并直接访问、修改私有变量。文章通过具体示例展示了如何获取View组件的onClick属性名称,以及如何调用AssetManager的addAssetPath方法,为读者提供了深入理解反射原理和应用的实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

反射获取变量: ReflectTool.getSubField(, , );

// 通过反射,获取View的在res/Layout布局中声明的onClick属性名称
// <Button android:id="@+id/button1" android:onClick="OpenLog" />

Button view = (Button)this.findViewById(R.id.button1);

Object mListenerInfo = getSubField(view, View.class, "mListenerInfo");
Object mOnClickListener = getSubField(mListenerInfo, "mOnClickListener");    
Object handlerName = getSubField(mOnClickListener, "val$handlerName");

handlerName为"OpenLog"

 反射调用函数方法:  ReflectTool.CallMethod(, , , );  

// 反射调用 AssetManager.addAssetPath(String path); // 添加Assets资源路径

String apkPath = "/sdcard/apps/1.apk";
assets = AssetManager.class.newInstance();		// 创建类实例
CallMethodX(assets, "addAssetPath", apkPath);	// 添加apk路径至Asset资源路径

反射工具类: 


package sci.apk.plugin;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.ArrayMap;
import android.view.View;

/** 反射,调用Object中的函数、获取Object中的指定变量 scimence */
public class ReflectTool
{
        /** 调用类静态方法 */
        public static Object CallStaticMethod(String className, String methodName, Object...param)
        {
            Object result = null;
            Method methodObj = null;
            Class<?> classType = null;
            try
            {
                classType = Class.forName(className);
                methodObj = classType.getMethod(methodName); 	// 获取类中的函数方法
                methodObj.setAccessible(true);
                result = methodObj.invoke(null, param);					// 反射调用函数方法classObj.methodName()
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
            if (classType == null) throw new IllegalStateException("Could not find Class " + className);
            if (methodObj == null) throw new IllegalStateException("Could not find Static method " + methodName + "() in the class " + classType.getName());
    
            return result;
        }

	/** 反射调用,Obj对象的methodName()函数 */
	public static Object CallMethod(Object Obj, String methodName)
	{
		if(Obj==null) throw new NullPointerException("Obj == null");
		
		Object result = null;
		Method methodObj = null;
		Class<?> classType = null;
		try
		{
			classType = Obj.getClass();
			methodObj = classType.getMethod(methodName); 	// 获取类中的函数方法
			result = methodObj.invoke(Obj);					// 反射调用函数方法classObj.methodName()
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		if (methodObj == null) throw new IllegalStateException("Could not find a method " + methodName + "() in the class " + classType.getName());
		
		return result;
	}
	
	/** 反射调用函数methodName(argClass, argObj) */
	public static Object CallMethod(Object Obj, String methodName, Class<?> argClass, Object argObj)
	{
		if(Obj==null) throw new NullPointerException("Obj == null");
		
		Object result = null;
		Method methodObj = null;
		Class<?> classType = null;
		try
		{
			classType = Obj.getClass();
			methodObj = classType.getMethod(methodName, argClass); 	// 获取类中的函数方法
			result = methodObj.invoke(Obj, argObj);					// 反射调用函数方法classObj.methodName(argObj)
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		if (methodObj == null)
			throw new IllegalStateException("Could not find a method " + methodName + "(" + argClass.getSimpleName() + ") in the class " + classType.getName());
		
		return result;
	}
	
	/** 反射调用函数methodName(...argObj) */
	public static Object CallMethodX(Object Obj, String methodName, Object... argObj)
	{
		if(Obj==null) throw new NullPointerException("Obj == null");
		
		Object result = null;
		Method methodObj = null;
		Class<?> classType = null;
		
		Class<?>[] argClass = null;
		try
		{
			// 获取参数类型
			List<Class<?>> list = new ArrayList<Class<?>>();
			for (Object arg : argObj)
			{
				list.add(arg.getClass());
			}
			argClass = new Class<?>[list.size()];
			list.toArray(argClass);
			
			classType = Obj.getClass();
			methodObj = classType.getMethod(methodName, argClass); 	// 获取类中的函数方法
			result = methodObj.invoke(Obj, argObj);					// 反射调用函数方法classObj.methodName(argObj)
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		if (methodObj == null)
		{
			String argsType = "";
			for (Class<?> cls : argClass)
			{
				argsType += cls.getSimpleName() + ", ";
			}
			if (argsType.length() > 2) argsType = argsType.substring(0, argsType.length() - 2);
			
			throw new IllegalStateException("Could not find a method " + methodName + "(" + argsType + ") in the class " + classType.getName());
		}
		
		return result;
	}
	
	
	/** 反射获取obj的成员变量fieldName(成员变量名获取,可在调试时动态查看) */
	public static Object getSubField(Object obj, String fieldName)
	{
		if(obj==null) throw new NullPointerException("obj == null");
		
		Object subObj = null;
		try
		{
			if (obj != null)
			{
				Field field = obj.getClass().getDeclaredField(fieldName);	// 获取成员变量对应的Field方法
				field.setAccessible(true);	// 设置为可访问
				subObj = field.get(obj);	// 通过Field方法从Object中提取子变量
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return subObj;
	}
	
	/** 反射获取obj的成员变量fieldName(成员变量名获取,可在调试时动态查看) */
	public static Object getSubField(Object obj, Class<?> cls, String fieldName)
	{
		if(obj==null) throw new NullPointerException("obj == null");
		Object subObj = null;
		try
		{
			if (obj != null)
			{
				Field field = cls.getDeclaredField(fieldName);	// 获取成员变量对应的Field方法
				field.setAccessible(true);	// 设置为可访问
				subObj = field.get(obj);	// 通过Field方法从Object中提取子变量
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return subObj;
	}
	
	/** 通过反射,获取View的在res/Layout布局中声明的onClick属性名称 */
	public static String get_onClickName(View view)
	{
		if(view==null) throw new NullPointerException("view == null");
		String Name = "";
		
		// 反射 View.mListenerInfo.mOnClickListener.val$handlerName
		try
		{
			Object mListenerInfo = getSubField(view, View.class, "mListenerInfo");
			Object mOnClickListener = getSubField(mListenerInfo, "mOnClickListener");
			Object handlerName = getSubField(mOnClickListener, "val$handlerName");
			Name = handlerName.toString();
		}
		catch (Exception e)
		{
//			e.printStackTrace();
		}
		
		return Name;
	}
	
	/** 获取apk包,对应的AssetManager */
	public static AssetManager getAssetManager(String apkPath)
	{
		AssetManager assets = null;
		try
		{
			assets = AssetManager.class.newInstance();		// 创建类实例
			CallMethodX(assets, "addAssetPath", apkPath);	// 添加apk路径至Asset资源路径
			
//			Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
//			addAssetPath.invoke(assets, apkPath);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return assets;
	}
	
//	public static ArrayMap<String, Object> GetMap(Bundle bundle)
//	{
//		ArrayMap<String, Object> map = null;
//		try
//		{
//			Object mMap = getSubField(bundle, "mMap");
//			map = (ArrayMap<String, Object>) mMap;
//		}
//		catch (Exception ex)
//		{
//			ex.printStackTrace();
//		}
//		return map;
//	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值