set Field Value - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

set Field Value

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

public class Main {

    public static void setFieldValue(Object object, String fieldName,
            Object value) {//from  w  w  w .  ja va  2 s.  c o m

        Field field = getDeclaredField(object, fieldName);

        field.setAccessible(true);

        try {
            field.set(object, value);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    public static Field getDeclaredField(Object object, String fieldName) {
        Field field = null;

        Class<?> clazz = object.getClass();

        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                return field;
            } catch (Exception e) {

            }
        }

        return null;
    }
}

Related Tutorials