Java Reflection Field Set setField(Object o, String fieldName, Object inject)

Here you can find the source of setField(Object o, String fieldName, Object inject)

Description

set Field

License

Apache License

Declaration

public static void setField(Object o, String fieldName, Object inject) 

Method Source Code


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

import java.lang.reflect.Field;

public class Main {
    public static void setField(Object o, String fieldName, Object inject) {
        Field field = getAccessibleField(fieldName, o.getClass());
        try {/*ww  w  .  jav a 2s .com*/
            field.set(o, inject);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private static Field getAccessibleField(String fieldName, Class<?> c) {
        Field field = null;
        while (c != null) {
            try {
                field = c.getDeclaredField(fieldName);
                field.setAccessible(true);
                break;
            } catch (NoSuchFieldException e) {
                c = c.getSuperclass();
            }
        }
        return field;
    }
}

Related

  1. setField(java.lang.Object toObj, String tcFieldName, java.lang.Object toNewValue)
  2. setField(Object instance, String fieldName, Object value)
  3. setField(Object instance, String name, Object obj)
  4. setField(Object instance, String sField, Object value)
  5. setField(Object item, Field f, Object value)
  6. setField(Object o, String fieldName, Object value)
  7. setField(Object o, String fieldName, Object value)
  8. setField(Object o, String name, Object value)
  9. setField(Object obj, Class fieldOwner, String fieldName, Object value)