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

Android examples for java.lang.reflect:Field Value

Description

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

Demo Code

/**//from  ww w. ja v a2s. c o m
 * 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 flag, set the value of that field to the flag
     * @param o our intended victim
     * @param c object class (proletariat, bourgeois, or plutocrat)
     * @param fieldName name of the field (it better match)
     * @param flag value to set
     * @throws NoSuchFieldException the field didn't match anything the class had
     * @throws IllegalAccessException I hope this never happens
     */
    public static void setFieldBooleanValue(Object o, Class c,
            String fieldName, boolean flag) throws NoSuchFieldException,
            IllegalAccessException {
        Field field = c.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.setBoolean(o, flag);
    }
}

Related Tutorials