Android examples for java.lang.reflect:Field
set Field by reflection
//package com.java2s; import java.lang.reflect.Field; import android.text.TextUtils; public class Main { private static final String TARGET_OBJECT = "target object: "; private static final String TARGET_OBJECT_CAN_NOT_BE_NULL = "target object can not be null"; public static void setField(String fieldName, Object target, Object value) throws Exception { if (TextUtils.isEmpty(fieldName)) { throw new RuntimeException("field name can not be empty"); }//from w w w .j a v a 2s . co m if (target == null) { throw new RuntimeException(TARGET_OBJECT_CAN_NOT_BE_NULL); } Field field = target.getClass().getDeclaredField(fieldName); if (field == null) { throw new RuntimeException(TARGET_OBJECT + target.getClass().getName() + " do not have this field: " + fieldName); } field.setAccessible(true); field.set(target, value); } }