Java Reflection Field Value Set setFieldValue(Class expectedType, Object target, String fieldName, T value)

Here you can find the source of setFieldValue(Class expectedType, Object target, String fieldName, T value)

Description

set Field Value

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static <T> T setFieldValue(Class<T> expectedType, Object target, String fieldName, T value) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2008 flowr.org - all rights reserved. This program and the accompanying materials are made available
 * under the terms of the Eclipse Public License (EPL) v1.0. The EPL is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors: flowr.org - initial API and implementation
 ******************************************************************************/

import java.lang.reflect.Field;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T setFieldValue(Class<T> expectedType, Object target, String fieldName, T value) {
        try {//ww w.  ja v  a  2  s.c o  m
            Class<? extends Object> targetClass = target.getClass();
            while (targetClass != null) {
                Field field = locateField(expectedType, targetClass, fieldName);
                if (field != null) {
                    T oldValue = (T) field.get(target);
                    field.set(target, value);
                    return oldValue;
                } else {
                    targetClass = targetClass.getSuperclass();
                }
            }
        } catch (Exception e) {
        }
        return null;
    }

    private static Field locateField(Class<?> expectedType, Class<?> targetClass, String fieldName) {
        try {
            Field field = targetClass.getDeclaredField(fieldName);
            if (field != null) {
                field.setAccessible(true);
                if (expectedType.isAssignableFrom(field.getType())) {
                    return field;
                }
            }
        } catch (Exception e) {
        }
        return null;
    }
}

Related

  1. setFieldValue(Class clazz, Object target, String fieldName, Object value)
  2. setFieldValue(Class clazz, E instance, Object value, String... names)
  3. setFieldValue(Class clazz, Object entity, String fieldName, V value)
  4. setFieldValue(Class clazz, String fieldName, Object value)
  5. setFieldValue(Class clazz, String fieldName, Object value)
  6. setFieldValue(Field f, Object target, Object value)
  7. setFieldValue(Field field, Object instance, T value)
  8. setFieldValue(Field field, Object obj, Object value)
  9. setFieldValue(Field field, Object object, Object value)