set Object Field by value - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

set Object Field by value

Demo Code


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

public class Main {
    public static void setObjectField(Object o, String fieldName,
            Object value) throws NoSuchFieldException,
            IllegalAccessException {
        Field f = getClassField(o.getClass(), fieldName);
        makeAccessible(f);//from  w w w . jav a2s.co  m
        f.set(o, value);
    }

    public static Field getClassField(Class clazz, String fieldName)
            throws NoSuchFieldException {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            Class superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            } else {
                return getClassField(superClass, fieldName);
            }
        }
    }

    private static void makeAccessible(Method method) {
        if (!Modifier.isPublic(method.getModifiers())
                || !Modifier.isPublic(method.getDeclaringClass()
                        .getModifiers())) {
            method.setAccessible(true);
        }
    }

    private static void makeAccessible(Field field) {
        if (!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass()
                        .getModifiers())) {
            field.setAccessible(true);
        }
    }
}

Related Tutorials