Java Reflection Field Set setField(final Object object, final String name, final Object value)

Here you can find the source of setField(final Object object, final String name, final Object value)

Description

set Field

License

Apache License

Declaration

public static void setField(final Object object, final String name, final Object value) 

Method Source Code

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

import java.lang.reflect.Field;

public class Main {
    public static void setField(final Object object, final String name, final Object value) {
        try {// w w  w. j a  v  a 2  s.  c o m
            final Field field = findField(object.getClass(), name);
            field.setAccessible(true);
            field.set(object, value);
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException(e);
        }
    }

    private static Field findField(final Class<?> clazz, final String name) throws ReflectiveOperationException {
        Class<?> theClazz = clazz;
        while (theClazz != null) {
            try {
                return theClazz.getDeclaredField(name);
            } catch (NoSuchFieldException e) {
                theClazz = theClazz.getSuperclass();
            }
        }

        throw new NoSuchFieldException(name);
    }
}

Related

  1. setField(final Object instance, final String fieldName, final T value)
  2. setField(final Object obj, final String fieldName, final int value)
  3. setField(final Object obj, final String fieldName, final Object value)
  4. setField(final Object obj, final String name, final Object value)
  5. setField(final Object obj, final String variableName, final Object variableValue)
  6. setField(final Object parent, final String name, final Object obj)
  7. setField(java.lang.Object toObj, String tcFieldName, java.lang.Object toNewValue)
  8. setField(Object instance, String fieldName, Object value)
  9. setField(Object instance, String name, Object obj)