定义:Reflection是java开发语言特性之一,它允许运行中的java程序对自身进行检测,自审,并能操作程序内部的属性和方法,Reflection是java被视为动态语言关键之一。允许程序从执行期的Reflection APIS取得任何已知名称的class内部信息,包含packages、type parameters、superclass、implement Interfaces、inner classes、outer class、fields、methods、constructors、modifiers,并可在执行期间执行instance,更变field内容,唤醒method。

反射过程中常用的类:     java反射所需要的类并不多,他们分别是:Class、Constructor、Object、Method、Field。     Class类:每个class都有一个相应的Class对象。也就是说,当我们编写一个类,编译完成后,在生成的.class文件中,就会产生一个Class对象,在运行期间如果我们需要产生某个类的对象,JVM就会检测该类型的Class对象是否已经被加载,如果没有被加载,则虚拟机会根据类名称找到并加载相对应的.class文件,一旦某个类型的Class对象加载到内存中,就可以用它来产生相应的对象。     Constructor类:封装了反射类的构造方法,提供该类单个构造方法和访问权限信息。     Object类:每个类都使用Object作为超类,所有的对象都实现这个类的方法。     Method类:提供有关类或者接口单独某个方法的信息,以及动态访问权限,所反映的方法可能是类方法或者实例方法以及抽象方法。     Field类:提供有关类或者结构单独属性的信息,以及动态访问权限,所反映的属性可能是类属性或者实例属性。

项目中的实际运用:     上次在讲述Android AIDL IPC通信的时候提到过,基于AIDL实现客户端被注册的view通过反射以及服务端传过来的数据达成一个交互过程。实现图片文字的显示过程。

    

客户端调用:         首先:我们需要实现我们要注册的MyImageView,继承自ImageView,主要用来图片显示。

package com.zlc.aidl.client;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

public class MyImageView extends ImageView{

	public MyImageView(Context context) {
		super(context);
	}

	@Override
	public void setImageBitmap(Bitmap bm) {
		// TODO Auto-generated method stub
		super.setImageBitmap(bm);
	}
}
package com.zlc.aidl.client;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

public class MyImageView extends ImageView{

	public MyImageView(Context context) {
		super(context);
	}

	@Override
	public void setImageBitmap(Bitmap bm) {
		// TODO Auto-generated method stub
		super.setImageBitmap(bm);
	}
}

然后:我们需要反射的工具类ReflectionInvoke.java,用来反射调用注册view对象里面的方法,通过服务端传过来的参数和对应方法名来进行反射调用。在工具类中包含一个InvokeKey的内部类,主要用来标示一个对象的某个方法,并保存到工具类集合里面,下次调用的时候不需要再进行寻找method的过程,直接invoke反射调用就行。

package com.zlc.aidl.client;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

import android.util.Log;

public class ReflectionInvoke {
	public static HashMap<InvokeKey, WeakReference<ReflectionInvoke>> reflections = new HashMap<ReflectionInvoke.InvokeKey, WeakReference<ReflectionInvoke>>();
	private Method method;
	private Class<?> clazz;
	private Class<?> parameterClasses[];

	static class InvokeKey {
		String className;
		String methodName;
		String[] paramsClassName;

		public InvokeKey(String className, String methodName, String[] paramsClassName) {
			this.className = className;
			this.methodName = methodName;
			this.paramsClassName = paramsClassName;
		}

		@Override
		public int hashCode() {
			// TODO Auto-generated method stub
			int ret = className.hashCode();
			ret = methodName.hashCode() + ret * 10;
			for (int i = 0; i < paramsClassName.length; i++) {
				ret = paramsClassName[i].hashCode() + ret * 10;
			}
			return ret;
		}

		@Override
		public boolean equals(Object o) {
			if (o instanceof InvokeKey) {
				InvokeKey key = (InvokeKey) o;
				if (!key.className.equals(className) || !key.methodName.equals(methodName)
						|| key.paramsClassName.length != paramsClassName.length) {
					return false;
				} else {
					for (int i = 0; i < paramsClassName.length; i++) {
						if (!key.paramsClassName[i].equals(paramsClassName[i]))
							return false;
					}
					return true;
				}
			}
			return false;
		}
	}

	Class<?> classForNameX(String name) throws Exception {
		if ("int".equals(name))
			return int.class;
		else if ("char".equals(name))
			return char.class;
		else if ("short".equals(name))
			return short.class;
		else if ("byte".equals(name))
			return byte.class;
		else if ("long".equals(name))
			return long.class;
		else if ("float".equals(name))
			return float.class;
		else if ("double".equals(name))
			return double.class;
		else if ("boolean".equals(name))
			return boolean.class;
		return Class.forName(name);
	}

	private ReflectionInvoke(InvokeKey key) throws Exception {
		clazz = Class.forName(key.className);
		parameterClasses = new Class[key.paramsClassName.length];
		for (int i = 0; i < parameterClasses.length; i++) {
			parameterClasses[i] = classForNameX(key.paramsClassName[i]);
		}
		method = clazz.getMethod(key.methodName, parameterClasses);
	}

	public static ReflectionInvoke getInvoker(String className, String methodName,
			List<String> argsClassName) {
		String[] arrayarges = new String[argsClassName.size()];
		argsClassName.toArray(arrayarges);
		return getInvoker(className, methodName, arrayarges);
	}

	public static ReflectionInvoke getInvoker(String className, String methodName, String... args) {
		ReflectionInvoke invoke = null;
		synchronized (reflections) {
			try {
				InvokeKey key = new InvokeKey(className, methodName, args);
				WeakReference<ReflectionInvoke> w = reflections.get(key);
				if (w == null ? true : (invoke = w.get()) == null) {
					invoke = new ReflectionInvoke(key);
					reflections.put(key, new WeakReference<ReflectionInvoke>(invoke));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return invoke;
	}

	public Object invokeNoException(Object obj, Object... args) {
		try {
			return method.invoke(obj, args);
		} catch (Exception e) {
			Log.d("Exception", "invoke error");
		}
		return null;
	}

	public Object invoke(Object obj, Object... args) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		Log.d("ReflectionInvoke", "invoke invoke invoke");
		return method.invoke(obj, args);
	}
}
package com.zlc.aidl.client;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

import android.util.Log;

public class ReflectionInvoke {
	public static HashMap<InvokeKey, WeakReference<ReflectionInvoke>> reflections = new HashMap<ReflectionInvoke.InvokeKey, WeakReference<ReflectionInvoke>>();
	private Method method;
	private Class<?> clazz;
	private Class<?> parameterClasses[];

	static class InvokeKey {
		String className;
		String methodName;
		String[] paramsClassName;

		public InvokeKey(String className, String methodName, String[] paramsClassName) {
			this.className = className;
			this.methodName = methodName;
			this.paramsClassName = paramsClassName;
		}

		@Override
		public int hashCode() {
			// TODO Auto-generated method stub
			int ret = className.hashCode();
			ret = methodName.hashCode() + ret * 10;
			for (int i = 0; i < paramsClassName.length; i++) {
				ret = paramsClassName[i].hashCode() + ret * 10;
			}
			return ret;
		}

		@Override
		public boolean equals(Object o) {
			if (o instanceof InvokeKey) {
				InvokeKey key = (InvokeKey) o;
				if (!key.className.equals(className) || !key.methodName.equals(methodName)
						|| key.paramsClassName.length != paramsClassName.length) {
					return false;
				} else {
					for (int i = 0; i < paramsClassName.length; i++) {
						if (!key.paramsClassName[i].equals(paramsClassName[i]))
							return false;
					}
					return true;
				}
			}
			return false;
		}
	}

	Class<?> classForNameX(String name) throws Exception {
		if ("int".equals(name))
			return int.class;
		else if ("char".equals(name))
			return char.class;
		else if ("short".equals(name))
			return short.class;
		else if ("byte".equals(name))
			return byte.class;
		else if ("long".equals(name))
			return long.class;
		else if ("float".equals(name))
			return float.class;
		else if ("double".equals(name))
			return double.class;
		else if ("boolean".equals(name))
			return boolean.class;
		return Class.forName(name);
	}

	private ReflectionInvoke(InvokeKey key) throws Exception {
		clazz = Class.forName(key.className);
		parameterClasses = new Class[key.paramsClassName.length];
		for (int i = 0; i < parameterClasses.length; i++) {
			parameterClasses[i] = classForNameX(key.paramsClassName[i]);
		}
		method = clazz.getMethod(key.methodName, parameterClasses);
	}

	public static ReflectionInvoke getInvoker(String className, String methodName,
			List<String> argsClassName) {
		String[] arrayarges = new String[argsClassName.size()];
		argsClassName.toArray(arrayarges);
		return getInvoker(className, methodName, arrayarges);
	}

	public static ReflectionInvoke getInvoker(String className, String methodName, String... args) {
		ReflectionInvoke invoke = null;
		synchronized (reflections) {
			try {
				InvokeKey key = new InvokeKey(className, methodName, args);
				WeakReference<ReflectionInvoke> w = reflections.get(key);
				if (w == null ? true : (invoke = w.get()) == null) {
					invoke = new ReflectionInvoke(key);
					reflections.put(key, new WeakReference<ReflectionInvoke>(invoke));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return invoke;
	}

	public Object invokeNoException(Object obj, Object... args) {
		try {
			return method.invoke(obj, args);
		} catch (Exception e) {
			Log.d("Exception", "invoke error");
		}
		return null;
	}

	public Object invoke(Object obj, Object... args) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		Log.d("ReflectionInvoke", "invoke invoke invoke");
		return method.invoke(obj, args);
	}
}

    其次:需要准备一个实现parcelable的对象,用来在两个进程之间传递方法名、方法参数等信息。

package com.zlc.aidl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;

public class JsonReflectionInvokParcelable implements Parcelable{
	public String objectId;
	public String methodname;
	public List<String> argsClassName;
	public List<Object> argsVaule;

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(objectId);
		dest.writeString(methodname);
		dest.writeList(argsClassName);
		dest.writeList(argsVaule);
	}

	public static final Parcelable.Creator<JsonReflectionInvokParcelable> CREATOR = new Parcelable.Creator<JsonReflectionInvokParcelable>() {
		public JsonReflectionInvokParcelable createFromParcel(Parcel in) {
			JsonReflectionInvokParcelable tp = new JsonReflectionInvokParcelable();
			tp.objectId = in.readString();
			tp.methodname = in.readString();
			tp.argsClassName = new ArrayList<String>();
			in.readList(tp.argsClassName, null);
			tp.argsVaule = new ArrayList<Object>();
			in.readList(tp.argsVaule, null);
			return tp;
		}

		public JsonReflectionInvokParcelable[] newArray(int size) {
			return new JsonReflectionInvokParcelable[size];
		}
	};

	public void clean() {
		for (Object o : argsVaule) {
			try {
				if (o instanceof ParcelFileDescriptor)
					((ParcelFileDescriptor) o).close();
				else if (o instanceof Bitmap)
					((Bitmap) o).recycle();
			} catch (IOException e) {
			}
		}
	}
}
package com.zlc.aidl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;

public class JsonReflectionInvokParcelable implements Parcelable{
	public String objectId;
	public String methodname;
	public List<String> argsClassName;
	public List<Object> argsVaule;

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(objectId);
		dest.writeString(methodname);
		dest.writeList(argsClassName);
		dest.writeList(argsVaule);
	}

	public static final Parcelable.Creator<JsonReflectionInvokParcelable> CREATOR = new Parcelable.Creator<JsonReflectionInvokParcelable>() {
		public JsonReflectionInvokParcelable createFromParcel(Parcel in) {
			JsonReflectionInvokParcelable tp = new JsonReflectionInvokParcelable();
			tp.objectId = in.readString();
			tp.methodname = in.readString();
			tp.argsClassName = new ArrayList<String>();
			in.readList(tp.argsClassName, null);
			tp.argsVaule = new ArrayList<Object>();
			in.readList(tp.argsVaule, null);
			return tp;
		}

		public JsonReflectionInvokParcelable[] newArray(int size) {
			return new JsonReflectionInvokParcelable[size];
		}
	};

	public void clean() {
		for (Object o : argsVaule) {
			try {
				if (o instanceof ParcelFileDescriptor)
					((ParcelFileDescriptor) o).close();
				else if (o instanceof Bitmap)
					((Bitmap) o).recycle();
			} catch (IOException e) {
			}
		}
	}
}

服务端调用

    再次:服务端发送数据之前检测并且封装参数的类型

……
public void callReflection(String json, String objId, String method,
			Object ...args) throws RemoteException {
		JsonReflectionInvokParcelable p = new JsonReflectionInvokParcelable();
		p.objectId = objId;
		p.methodname = method;
		p.argsClassName = new ArrayList<String>();
		p.argsVaule = new ArrayList<Object>();
		Log.d(TAG, "callReflection222 json=" + json);
		for (int i = 0; i < args.length; i++) {
			Object o = args[i];
			@SuppressWarnings("rawtypes")
			Class clazz = o.getClass();
			if (clazz.isPrimitive() || o instanceof Parcelable || o instanceof String
					|| o instanceof Integer || o instanceof Short || o instanceof Float
					|| o instanceof Double || o instanceof Character) {
				p.argsClassName.add(clazz.getCanonicalName());
				p.argsVaule.add(o);
			} else {
				throw new RuntimeException("args only support primitives and String");
			}
		}
		callback.onReflectionCallback(p, json);
		Log.d(TAG, "callReflection222 end json=" + json);
	}
……
……
public void callReflection(String json, String objId, String method,
			Object ...args) throws RemoteException {
		JsonReflectionInvokParcelable p = new JsonReflectionInvokParcelable();
		p.objectId = objId;
		p.methodname = method;
		p.argsClassName = new ArrayList<String>();
		p.argsVaule = new ArrayList<Object>();
		Log.d(TAG, "callReflection222 json=" + json);
		for (int i = 0; i < args.length; i++) {
			Object o = args[i];
			@SuppressWarnings("rawtypes")
			Class clazz = o.getClass();
			if (clazz.isPrimitive() || o instanceof Parcelable || o instanceof String
					|| o instanceof Integer || o instanceof Short || o instanceof Float
					|| o instanceof Double || o instanceof Character) {
				p.argsClassName.add(clazz.getCanonicalName());
				p.argsVaule.add(o);
			} else {
				throw new RuntimeException("args only support primitives and String");
			}
		}
		callback.onReflectionCallback(p, json);
		Log.d(TAG, "callReflection222 end json=" + json);
	}
……

    最后:从服务端调用客户端注册view的某个指定方法

private final IMyAidlService.Stub mBinder = new IMyAidlService.Stub() {

		@Override
		public void registerClient(AIDLCallback cb) throws RemoteException {
			Log.d(TAG, "registerClient");
			callback = cb;
			Bitmap bmp = BitmapFactory.decodeFile("/data/data/com.zlc.aidl.server/files/1.jpg");
			callReflection("just for test","myImageView","setImageBitmap",bmp);
			cb.asBinder().linkToDeath(new DeathRecipient() {

				@Override
				public void binderDied() {
					// TODO Auto-generated method stub
					try {
						Log.i(TAG, "[ServiceAIDLImpl]binderDied.");
					} catch (Throwable e) {
					}
				}
			}, 0);
			
		}
	};
private final IMyAidlService.Stub mBinder = new IMyAidlService.Stub() {

		@Override
		public void registerClient(AIDLCallback cb) throws RemoteException {
			Log.d(TAG, "registerClient");
			callback = cb;
			Bitmap bmp = BitmapFactory.decodeFile("/data/data/com.zlc.aidl.server/files/1.jpg");
			callReflection("just for test","myImageView","setImageBitmap",bmp);
			cb.asBinder().linkToDeath(new DeathRecipient() {

				@Override
				public void binderDied() {
					// TODO Auto-generated method stub
					try {
						Log.i(TAG, "[ServiceAIDLImpl]binderDied.");
					} catch (Throwable e) {
					}
				}
			}, 0);
			
		}
	};

具体反射的其他一些用途和使用方式,大家可以去问问度娘和谷哥,这有个例子讲述了大部分使用方法。

最后附上反射使用实例的源码,图片自己下载一张存放到/data/data/com.zlc.aidl.server/files/目录下,如果没有files目录,可通过代码创建或者通过linux命令创建。