Java Reflection Field Set setField(Object obj, String fieldName, Object fieldValue)

Here you can find the source of setField(Object obj, String fieldName, Object fieldValue)

Description

Utility to set field in object if there is no public setter for it.

License

Apache License

Parameter

Parameter Description
obj Object to be modified
fieldName name of object's field
fieldValue value to be set for field

Exception

Parameter Description
SecurityException an exception
NoSuchFieldException an exception
IllegalArgumentException an exception
IllegalAccessException an exception

Declaration

public static void setField(Object obj, String fieldName, Object fieldValue)
        throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException 

Method Source Code

//package com.java2s;
/*/*from w ww.  j  a  va2 s  .  c  o m*/
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.lang.reflect.Field;

public class Main {
    /**
     * Utility to set field in object if there is no public setter for it.
     * It's not recommended to use this method.
     * FIXME: remove this workaround after gradle API changed
     *
     * @param obj        Object to be modified
     * @param fieldName  name of object's field
     * @param fieldValue value to be set for field
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void setField(Object obj, String fieldName, Object fieldValue)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        final Field field = obj.getClass().getDeclaredField(fieldName);
        final boolean isAccessible = field.isAccessible();
        field.setAccessible(true);
        field.set(obj, fieldValue);
        field.setAccessible(isAccessible);
    }
}

Related

  1. setField(Object o, String name, Object value)
  2. setField(Object obj, Class fieldOwner, String fieldName, Object value)
  3. setField(Object obj, Field field, Object value)
  4. setField(Object obj, Object value, String fieldName)
  5. setField(Object obj, Object value, String fieldName)
  6. setField(Object obj, String fieldName, Object val)
  7. setField(Object obj, String fieldname, Object value)
  8. setField(Object obj, String fieldName, Object value)
  9. setField(Object obj, String fieldName, Object value)