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

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

Description

set Field

License

Open Source License

Declaration

public static void setField(Object obj, String name, Object value) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

public class Main {
    public static void setField(Object obj, String name, Object value) {
        try {//from   ww w . ja v a2s .co  m
            getFieldAndEnsureItsAccessible(obj, name).set(obj, value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static Field getFieldAndEnsureItsAccessible(Object obj, String name) {
        Class klass = obj instanceof Class ? (Class) obj : obj.getClass();
        Field field = null;
        do {
            try {
                field = klass.getDeclaredField(name);
            } catch (NoSuchFieldException e) {
            }
            klass = klass.getSuperclass();
            if (klass == null) {
                throw new NoSuchFieldError();
            }
        } while (field == null);

        if (!field.isAccessible()) {
            field.setAccessible(true);
        }

        try {
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        return field;
    }
}

Related

  1. setField(Object obj, String fieldName, Object val)
  2. setField(Object obj, String fieldname, Object value)
  3. setField(Object obj, String fieldName, Object value)
  4. setField(Object obj, String fieldName, Object value)
  5. setField(Object obj, String fieldName, Object value, Class valueClass)
  6. setField(Object obj, String name, Object value)
  7. setField(Object object, Class clazz, String fieldName, Object value)
  8. setField(Object object, Class clazz, String fieldName, Object value)
  9. setField(Object object, Field field, Object value)