Java Reflection Field Value Set setFieldValue(String inField, Object inObject, Object inValue)

Here you can find the source of setFieldValue(String inField, Object inObject, Object inValue)

Description

set Field Value

License

Open Source License

Declaration

public static void setFieldValue(String inField, Object inObject, Object inValue)
            throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    public static void setFieldValue(String inField, Object inObject, Object inValue)
            throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {

        final Class<?> theClass = (Class<?>) (inObject instanceof Class ? inObject : inObject.getClass());

        final Field theField = theClass.getDeclaredField(inField);

        setFieldValue(theField, Modifier.isStatic(theField.getModifiers()) ? null : inObject, inValue);
    }//from   w w  w  .ja v a2  s  .c o  m

    public static void setFieldValue(Field inField, Object inObject, Object inValue)
            throws IllegalArgumentException, IllegalAccessException {

        final boolean isAccessible = inField.isAccessible();
        if (!isAccessible) {
            inField.setAccessible(true);
        }

        try {

            inField.set(inObject, inValue);
        } finally {
            // why reset this beahviour; will setAccessible(true) anyways again on next invocation
            //         if (!isAccessible) {
            //            inField.setAccessible(false);
            //         }
        }
    }

    public static boolean isStatic(Class<?> inClass) {

        return inClass != null && Modifier.isStatic(inClass.getModifiers());
    }

    public static boolean isStatic(Method inMethod) {

        return inMethod != null && Modifier.isStatic(inMethod.getModifiers());
    }

    public static boolean isStatic(Field inField) {
        return inField != null && Modifier.isStatic(inField.getModifiers());
    }
}

Related

  1. setFieldValue(Object target, String fieldName, Object value)
  2. setFieldValue(Object target, String fieldName, Object value)
  3. setFieldValue(Object target, String fieldName, String fieldValue)
  4. setFieldValue(Object target, String fname, Class ftype, Object fvalue)
  5. setFieldValue(String fieldName, int fieldValue, Object board)
  6. setFieldValue(String name, Object instance, int value, Class cl)
  7. setFieldValue(String name, String obfuscatedName, Class clazz, Object object, Object value)
  8. setFieldvalue(T instance, E value, Field field)
  9. setFieldValue_internal(Object bean, Field field, Object value)