まめーじぇんと@Tech

技術ネタに関して (Android, GAE, Angular). Twitter: @mame01122

Androidの自動テストで使うReflectionのUtilクラス

Androidの自動テストを書いていて、
Reflectionを使ってprivateフィールドにアクセスする機会があったので、メモ。

public class ReflectionUtil {

	public static <T> Object getValue(Class<T> className, String fieldName,
			Object targetObject) {

		Object result = null;

		if (targetObject != null) {
			try {
				Field field = className.getDeclaredField(fieldName);
				field.setAccessible(true);
				result = field.get(targetObject);
				return result;
			} catch (Exception e) {
				return null;
			}
		}

		return null;
	}

	public static <T> void setFieldValue(Class<T> className,
			Object targetObject, String fieldName, Object targetValue) {

		if (targetObject != null) {
			try {
				Field field = className.getDeclaredField(fieldName);
				field.setAccessible(true);
				field.set(targetObject, targetValue);
			} catch (Exception e) {

			}
		}
	}

使い方は下記の通り。

■値のSet

ReflectionUtil.setFieldValue(MyActivity.class, targetInstance
		"mProgressDialog", mProgressDialog);

第一引数はターゲットとなるclass名、
第二引数はそのclassのインスタンス (Test case内でインスタンスを作成)
第三引数は対象となるフィールド名(どんな形でもOK)
第四引数は、設置したい値(これもTest case内でインスタンスを作成)


■値のGet

boolean isExistingDataAvailable = (Boolean) ReflectionUtil
		.getValue(MyActivity.class, "isExistingDataAvailable", targetInstance);

第一引数はターゲットとなるclass名、
第二引数は対象となるフィールド名(どんな形でもOK)
第三引数はそのclassのインスタンス (Test case内でインスタンスを作成))