Java Reflection Field Value Set setFieldValue(Object input, Object value, String fieldName)

Here you can find the source of setFieldValue(Object input, Object value, String fieldName)

Description

set Field Value

License

Open Source License

Declaration

public static Object setFieldValue(Object input, Object value, String fieldName) throws Exception 

Method Source Code


//package com.java2s;
/*/*from  w w  w. j  ava2s  .  c o m*/
* Copyright: (c) Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/lexevs-remote/LICENSE.txt for details.
*/

import java.lang.reflect.Field;

public class Main {
    public static Object setFieldValue(Object input, Object value, String fieldName) throws Exception {
        Class searchClass = input.getClass();

        while (searchClass != null) {
            Field[] fields = searchClass.getDeclaredFields();
            for (Field field : fields) {
                if (field.getName().equals(fieldName)) {
                    field.setAccessible(true);
                    //Check to see if we're trying to set a int, long, etc with a String
                    if (field.getType().getName().equals("java.lang.Long")) {
                        if (value instanceof String) {
                            field.set(input, Long.getLong((String) value));
                        } else {
                            field.set(input, value);
                        }
                    } else if (field.getType().getName().equals("java.lang.Integer")) {
                        if (value instanceof String) {
                            field.set(input, Integer.getInteger((String) value));
                        } else {
                            field.set(input, value);
                        }
                    } else {
                        field.set(input, value);
                    }
                }
            }
            searchClass = searchClass.getSuperclass();
        }
        return input;
    }
}

Related

  1. setFieldValue(Map map, Class cls)
  2. setFieldValue(Object bean, Field field, Object value)
  3. setFieldValue(Object bean, Field field, Object value)
  4. setFieldValue(Object bean, String field, Object value)
  5. setFieldValue(Object host, Field f, Object value)
  6. setFieldValue(Object instance, Field field, Object value)
  7. setFieldValue(Object instanceContainingField, String fieldName, Object fieldValue)
  8. setFieldValue(Object o, Class baseClass, Class fieldType, T value)
  9. SetFieldValue(Object o, String field, Object object)