Java Reflection Field Set setFieldObjectValue(Class targetClass, Object target, String fieldName, Object value)

Here you can find the source of setFieldObjectValue(Class targetClass, Object target, String fieldName, Object value)

Description

Reflection utility: sets the field value of given object using target class.

License

Open Source License

Declaration

public static void setFieldObjectValue(Class<?> targetClass, Object target, String fieldName, Object value) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * 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.// w  w  w . ja v a  2s  .c om
 *******************************************************************************/

import java.lang.reflect.Field;

public class Main {
    /**
     * Reflection utility: sets the field value of given object using target class.
     */
    public static void setFieldObjectValue(Class<?> targetClass, Object target, String fieldName, Object value) {
        try {
            Field field = targetClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(target, value);
        } catch (Throwable e) {
            throw new RuntimeException(
                    "Unable to get field '" + fieldName + "' from class " + targetClass.getName(), e);
        }
    }

    /**
     * Reflection utility: sets the field value of given object.
     */
    public static void setFieldObjectValue(Object target, String fieldName, Object value) {
        if (target != null) {
            setFieldObjectValue(target.getClass(), target, fieldName, value);
        } else {
            throw new NullPointerException("target must not be null");
        }
    }
}

Related

  1. setFieldForAnnotation(Object target, Class annotation, Object value)
  2. setFieldHelper(Object o, String name, Object v)
  3. setFieldIfExists(final Object instance, final String fieldName, final Object value)
  4. setFieldObject(Class clazz, String field, Object object, Object newObj)
  5. setFieldObject(Class target, Object targetObject, String fieldName, Object object)
  6. setFieldPrimitive(Object target, Field field, Object value)
  7. setFields(Field field, Object value, Object config)
  8. setFields(final Map fields, final Object target)
  9. setFieldStatic(final Object pBean, final String fieldname, final Object pInject)