Java Utililty Methods Reflection Field Value Set

List of utility methods to do Reflection Field Value Set

Description

The list of methods to do Reflection Field Value Set are organized into topic(s).

Method

voidsetFieldValue(Object obj, String fieldName, Object value)
Reads the value of a field.
try {
    Class clazz;
    if (obj instanceof Class) {
        clazz = (Class) obj;
    } else {
        clazz = obj.getClass();
    Field field = clazz.getDeclaredField(fieldName);
...
voidsetFieldValue(Object obj, String fieldname, Object value)
set Field Value
Class<?> clazz = obj.getClass();
do {
    try {
        Field field = clazz.getDeclaredField(fieldname);
        field.setAccessible(true);
        field.set(obj, value);
    } catch (Throwable t) {
} while ((clazz = clazz.getSuperclass()) != null);
voidsetFieldValue(Object obj, String fieldName, Object value)

Sets the field value for the given object instance.

Field field = getField(obj, fieldName);
field.setAccessible(true);
field.set(obj, value);
voidsetFieldValue(Object obj, String fieldName, Object value)
Set the given field on the specified object.
try {
    getField(obj, fieldName).set(obj, value);
} catch (IllegalAccessException e) {
    e.printStackTrace();
    throw new RuntimeException("Field cannot be accessed", e);
booleansetFieldValue(Object obj, String fieldName, Object value)
set Field Value
boolean result = true;
try {
    Field field = obj.getClass().getDeclaredField(fieldName);
    boolean access = field.isAccessible();
    field.setAccessible(true);
    field.set(obj, value);
    field.setAccessible(access);
} catch (ReflectiveOperationException e) {
...
voidsetFieldValue(Object obj, String fieldName, String fieldValue)
set Field Value
Field field = getField(obj.getClass(), fieldName);
if (field != null) {
    field.setAccessible(true);
    field.set(obj, fieldValue);
voidsetFieldValue(Object obj, String name, Object value)
set Field Value
Field field = getField(obj.getClass(), name);
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
    field.set(obj, value);
} finally {
    field.setAccessible(accessible);
voidsetFieldValue(Object object, Field field, Object value)
set Field Value
try {
    setAccessibleIfNeeded(field);
    field.set(object, value);
} catch (final Exception e) {
    throw new RuntimeException(e);
voidsetFieldValue(Object object, String fieldName, Object fieldValue)
set Field Value
try {
    Field field = object.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(object, fieldValue);
    field.setAccessible(false);
} catch (Exception e) {
    try {
        Field field = object.getClass().getSuperclass().getDeclaredField(fieldName);
...
voidsetFieldValue(Object object, String fieldName, Object fieldValue)
set Field Value
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);