Java Reflection Field Value Set setFieldValue(Object obj, String fieldName, Object value)

Here you can find the source of setFieldValue(Object obj, String fieldName, Object value)

Description

Set the given field on the specified object.

License

BSD License

Declaration

public static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException 

Method Source Code


//package com.java2s;
/*L//from  w ww .j a va2 s .c om
 *  Copyright SAIC
 *
 *  Distributed under the OSI-approved BSD 3-Clause License.
 *  See http://ncip.github.com/cabio/LICENSE.txt for details.
 */

import java.lang.reflect.Field;

public class Main {
    /**
     * Set the given field on the specified object. If the field is
     * private, this subverts the security manager to set the value anyway.
     */
    public static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException {
        try {
            getField(obj, fieldName).set(obj, value);
        } catch (IllegalAccessException e) {
            // shouldnt happen since getField sets the field accessible
            e.printStackTrace();
            throw new RuntimeException("Field cannot be accessed", e);
        }
    }

    /**
     * Set the given attribute on the specified object, 
     * using the public setter method.
     */
    public static void set(Object obj, String attributeName, Object value) throws Exception {
        Class[] argTypes = { value.getClass() };
        Object[] argValues = { value };
        String methodName = getAccessor("set", attributeName);
        obj.getClass().getMethod(methodName, argTypes).invoke(obj, argValues);
    }

    private static Field getField(Object obj, String fieldName) throws NoSuchFieldException {

        final Field fields[] = obj.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (fieldName.equals(field.getName())) {
                field.setAccessible(true);
                return field;
            }
        }

        throw new NoSuchFieldException(fieldName);
    }

    private static String getAccessor(String prefix, String attributeName) throws NoSuchMethodException {
        String firstChar = attributeName.substring(0, 1).toUpperCase();
        return prefix + firstChar + attributeName.substring(1);
    }
}

Related

  1. setFieldValue(Object obj, Field field, Object value)
  2. setFieldValue(Object obj, String field, Object value)
  3. setFieldValue(Object obj, String fieldName, Object value)
  4. setFieldValue(Object obj, String fieldname, Object value)
  5. setFieldValue(Object obj, String fieldName, Object value)
  6. setFieldValue(Object obj, String fieldName, Object value)
  7. setFieldValue(Object obj, String fieldName, String fieldValue)
  8. setFieldValue(Object obj, String name, Object value)
  9. setFieldValue(Object object, Field field, Object value)