Java Reflection Field Set setFieldObject(Class target, Object targetObject, String fieldName, Object object)

Here you can find the source of setFieldObject(Class target, Object targetObject, String fieldName, Object object)

Description

set Field Object

License

Open Source License

Declaration

public static void setFieldObject(Class<?> target, Object targetObject, String fieldName, Object object) 

Method Source Code

//package com.java2s;
/**/*  w w w.jav a  2  s  . c o  m*/
 * 
 * This software is part of the MightyBiomesAPI
 * 
 * Copyright (c) 2013 Cybermaxke
 * 
 * MightyBiomesAPI is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * any later version.
 * 
 * MightyBiomesAPI 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MightyBiomesAPI. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Main {
    public static void setFieldObject(Class<?> target, Object targetObject, String fieldName, Object object) {
        try {
            Field field = target.getDeclaredField(fieldName);
            field.setAccessible(true);

            Field field1 = Field.class.getDeclaredField("modifiers");
            field1.setAccessible(true);
            field1.set(field, field.getModifiers() & ~Modifier.FINAL);

            field.set(targetObject, object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related

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