given an object, its class, a fieldName and a value, set the value of that field to the object - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

given an object, its class, a fieldName and a value, set the value of that field to the object

Demo Code

/**//from www . j a  v  a2 s.c om
 * utility functions to extract and set fields in objects using java reflection
 * @author Matthew
 * Copyright (c) 2013 Visible Automation LLC.  All Rights Reserved.
 *
 */
//package com.java2s;
import java.lang.reflect.Field;

public class Main {
    /**
     * given an object, its class, a fieldName and a value, set the value of that field to the object
     * @param o our intended victim
     * @param c object class (proletariat, bourgeois, or plutocrat)
     * @param fieldName name of the field (it better match)
     * @param value value to set
     * @throws NoSuchFieldException the field didn't match anything the class had
     * @throws IllegalAccessException I hope this never happens
     */
    public static void setFieldValue(Object o, Class c, String fieldName,
            Object value) throws NoSuchFieldException,
            IllegalAccessException {
        Field field = c.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(o, value);
    }
}

Related Tutorials