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

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

Description

set Field Value

License

Open Source License

Declaration

public static void setFieldValue(Class<?> clazz, String fieldName, Object value) 

Method Source Code

//package com.java2s;
/**/*from w w  w.  j  a  v  a  2s.c om*/
 * Helios, OpenSource Monitoring
 * Brought to you by the Helios Development Group
 *
 * Copyright 2014, Helios Development Group and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org. 
 *
 */

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

public class Main {
    public static void setFieldValue(Class<?> clazz, String fieldName, Object value) {
        setFieldValue(clazz, null, fieldName, value);
    }

    public static void setFieldValue(Class<?> clazz, Object target, String fieldName, Object value) {
        try {
            Field targetField = clazz.getDeclaredField(fieldName);
            boolean modifiedAccess = false;
            boolean modifiedWriteability = false;
            try {
                if (!targetField.isAccessible()) {
                    targetField.setAccessible(true);
                    modifiedAccess = true;
                }
                if (Modifier.isFinal(targetField.getModifiers())) {
                    targetField = setFieldEditable(clazz, fieldName);
                    modifiedWriteability = true;
                }
                if (targetField.getType().isPrimitive()) {
                    setFieldPrimitive(target, targetField, value);
                } else {
                    targetField.set(target, value);
                }
            } finally {
                if (modifiedAccess)
                    targetField.setAccessible(false);
                if (modifiedWriteability)
                    setFieldReadOnly(clazz, fieldName);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Sets a field in a class to be modifiable regardless of finality or privacy
     * @param clazz The class to modify
     * @param fieldName The name of the field to modify
     * @return the modified field
     */
    public static Field setFieldEditable(Class<?> clazz, String fieldName) {
        try {
            Field targetField = clazz.getDeclaredField(fieldName);
            Field modifierField = Field.class.getDeclaredField("modifiers");
            targetField.setAccessible(true);
            modifierField.setAccessible(true);
            modifierField.setInt(targetField, targetField.getModifiers() & ~Modifier.FINAL);
            return targetField;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void setFieldPrimitive(Object target, Field field, Object value) {
        try {
            final Class<?> c = field.getType();
            if (c == boolean.class) {
                field.setBoolean(target, (Boolean) value);
            } else if (c == byte.class) {
                field.setByte(target, ((Number) value).byteValue());
            } else if (c == char.class) {
                field.setChar(target, (Character) value);
            } else if (c == short.class) {
                field.setShort(target, ((Number) value).shortValue());
            } else if (c == int.class) {
                field.setInt(target, ((Number) value).intValue());
            } else if (c == float.class) {
                field.setFloat(target, ((Number) value).floatValue());
            } else if (c == long.class) {
                field.setLong(target, ((Number) value).longValue());
            } else if (c == double.class) {
                field.setDouble(target, ((Number) value).doubleValue());
            } else {
                throw new RuntimeException("WTF ? --->  [" + c.getName() + "]");
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }

    /**
     * Reverses the changes made in {@link #setFieldEditable(Class, String)}
     * @param clazz The class to modify
     * @param fieldName The name of the field to modify
     */
    public static void setFieldReadOnly(Class<?> clazz, String fieldName) {
        try {
            Field targetField = clazz.getDeclaredField(fieldName);
            Field modifierField = Field.class.getDeclaredField("modifiers");
            targetField.setAccessible(true);
            modifierField.setAccessible(true);
            modifierField.setInt(targetField, targetField.getModifiers() | Modifier.FINAL);
            modifierField.setAccessible(false);
            targetField.setAccessible(false);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related

  1. setFieldValue(Class c, Object instance, String name, Object value)
  2. setFieldValue(Class clazz, Object instance, String fieldName, T value)
  3. setFieldValue(Class clazz, Object target, String fieldName, Object value)
  4. setFieldValue(Class clazz, E instance, Object value, String... names)
  5. setFieldValue(Class clazz, Object entity, String fieldName, V value)
  6. setFieldValue(Class clazz, String fieldName, Object value)
  7. setFieldValue(Class expectedType, Object target, String fieldName, T value)
  8. setFieldValue(Field f, Object target, Object value)
  9. setFieldValue(Field field, Object instance, T value)