Java Reflection Field Value Set setFieldValueX(Object target, String field, Object value)

Here you can find the source of setFieldValueX(Object target, String field, Object value)

Description

set Field Value X

License

Apache License

Declaration

public final static void setFieldValueX(Object target, String field, Object value) 

Method Source Code

//package com.java2s;
/*//from  www.j a va 2  s.  c  o m
 * BJAF - Beetle J2EE Application Framework
 * ???J2EE???????????
 * ??????2003-2015 ??? (www.beetlesoft.net)
 * 
 * ??????????????????
 *<http://www.apache.org/licenses/LICENSE-2.0>
 *????????????????????????
 *
 * ???????????????????????????????
 * ??? <yuhaodong@gmail.com/>.
 */

import java.lang.reflect.Field;

import java.util.ArrayList;
import java.util.Arrays;

import java.util.List;

public class Main {

    public final static void setFieldValueX(Object target, String field, Object value) {
        try {
            // Class<?> obj = target.getClass();
            Field[] fields = getObjAllFields(target);
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                if (field.equals(fields[i].getName())) {
                    fields[i].set(target, value);
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Field[] getObjAllFields(Object object) {
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }
}

Related

  1. setFieldValue_internal(Object bean, Field field, Object value)
  2. setFieldValueForObject(Object object, String fieldName, Object value)
  3. setFieldValues(Object bean, Map valMap)
  4. setFieldValueWithPath(Object object, String path, Object value)
  5. setFieldValueWithSetterMethod(Object target, Object value, Class clazz, Field field)