您的位置:首页 > 移动开发 > Android开发

在Android中使用反射获取并修改private static final成员

2015-12-12 22:21 645 查看
import android.app.Instrumentation;
import android.test.InstrumentationTestCase;
import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
* Created by mark_chen on 2015/12/11.
* 1.使用了AndroidStudio自带的单元测试功能
*  a)在(androidTest)包中创建类
*  b)继承InstrumentationTestCase
*  c)创建以test开头的方法
*  d)右击本类可以直接运行
*
*  2.使用反射获取并修改某个类的私有静态终态(private static final)非基本类型的成员变量
*    ,获取某个成员的类型和修饰符
*    a) 使用a.getClass().getDeclaredField("属性名")获取A类的Field对象
*    b) field.setAccessible(true)设置feild可访问
*    c) 使用feild.set()方法修改某个成员
*    d) 使用Modifier.toString(feild.getModifiers())获取feild的Modifies对象
* */
public class TestClass extends InstrumentationTestCase {
public void test() {
Log.e("test","Android单元测试");

A a = new A();
Field field = null;
try {
field = a.getClass().getDeclaredField("a");
field.setAccessible(true);
field.set(a, 2);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
Log.e("test",a.getA()+"");
Log.e("test", Modifier.toString(field.getModifiers()));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: