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

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

Description

set Field

License

Apache License

Declaration

public static void setField(String name, Object target, 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(String name, Object target, Object value) {
        try {/*from w w  w. java 2 s .  co  m*/
            Class<?> targetClass = target.getClass();
            Field field = targetClass.getDeclaredField(name);
            boolean unlocked = false;
            if (!field.isAccessible()) {
                field.setAccessible(true);
                unlocked = true;
            }
            field.set(target, value);
            if (unlocked) {
                field.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. setField(Object targetObject, String fieldName, Object value, boolean failIfError)
  2. setField(String field, Object object, Object value)
  3. setField(String field, Object value)
  4. setField(String fieldName, Object instance, Class instanceClass, Object value)
  5. setField(String fieldName, Object instance, Object value)
  6. setField(String name, Object target, Object value)
  7. setField(T object, Field field, ResourceBundle bundle)
  8. setFieldAccessible(Class clazz, String... names)
  9. setFieldAccessible(Field field)