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

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

Description

set Field Value

License

Apache License

Declaration

public static void setFieldValue(Object receiver, String fieldName, Object value) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;

public class Main {
    public static void setFieldValue(Object receiver, String fieldName, Object value) {
        Field field = getField(receiver, fieldName);

        if (field == null) {
            return;
        }/*  w ww.ja  va2s .  com*/
        try {
            field.set(receiver, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    private static Field getField(Object receiver, String fieldName) {
        if (receiver == null) {
            return null;
        }
        return getFieldByClass(receiver.getClass(), fieldName);
    }

    private static Field getFieldByClass(Class<?> clazz, String fieldName) {
        if (clazz == null || fieldName == null) {
            return null;
        }
        try {
            return clazz.getField(fieldName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. setFieldValue(Object object, String fieldName, Object value)
  2. setFieldValue(Object object, String name, Object value)
  3. setFieldValue(Object object, String name, Object value)
  4. setFieldValue(Object objectInstance, String fieldName, Object valueToSet)
  5. setFieldValue(Object pojo, Field field, Object value)
  6. setFieldValue(Object target, Class targetClass, String fieldName, Object value)
  7. setFieldValue(Object target, Field field, Object newValue)
  8. setFieldValue(Object target, Field field, Object value)
  9. setFieldValue(Object target, Object mock, final Field field)