Java Reflection Field Value Set setFieldValue(Class clazz, Object entity, String fieldName, V value)

Here you can find the source of setFieldValue(Class clazz, Object entity, String fieldName, V value)

Description

set Field Value

License

Apache License

Declaration

public static <V> boolean setFieldValue(Class<?> clazz, Object entity, String fieldName, V value) 

Method Source Code

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

import java.lang.reflect.Field;

public class Main {
    public static <E, V> boolean setFieldValue(E entity, String fieldName, V value) {
        return setFieldValue(entity.getClass(), entity, fieldName, value);
    }/*from  ww  w.  j a v a2 s.  c o  m*/

    public static <V> boolean setFieldValue(Class<?> clazz, Object entity, String fieldName, V value) {
        try {
            Field f = clazz.getDeclaredField(fieldName);
            f.setAccessible(true);
            f.set(entity, value);
            return true;
        } catch (Exception ex) {
            throw new RuntimeException("Cannot set field " + fieldName + " value to " + value, ex);
        }
    }
}

Related

  1. setFieldValue(Class c, Object instance, String name, Object value)
  2. setFieldValue(Class clazz, Object instance, String fieldName, T value)
  3. setFieldValue(Class clazz, Object target, String fieldName, Object value)
  4. setFieldValue(Class clazz, E instance, Object value, String... names)
  5. setFieldValue(Class clazz, String fieldName, Object value)
  6. setFieldValue(Class clazz, String fieldName, Object value)
  7. setFieldValue(Class expectedType, Object target, String fieldName, T value)
  8. setFieldValue(Field f, Object target, Object value)