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

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

Description

set Field

License

Apache License

Declaration

public static void setField(Object o, String name, 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(Object o, String name, Object value) {
        try {//from  w  w w  . j av a 2 s .com
            field(o, name).set(o, value);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private static Field field(Object o, String name) throws NoSuchFieldException {
        return field(name, o.getClass());
    }

    private static Field field(String name, Class klass) throws NoSuchFieldException {
        if (klass == null) {
            return null;
        }
        Field[] fields = klass.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(name)) {
                field.setAccessible(true);
                return field;
            }
        }
        return field(name, klass.getSuperclass());
    }
}

Related

  1. setField(Object instance, String sField, Object value)
  2. setField(Object item, Field f, Object value)
  3. setField(Object o, String fieldName, Object inject)
  4. setField(Object o, String fieldName, Object value)
  5. setField(Object o, String fieldName, Object value)
  6. setField(Object obj, Class fieldOwner, String fieldName, Object value)
  7. setField(Object obj, Field field, Object value)
  8. setField(Object obj, Object value, String fieldName)
  9. setField(Object obj, Object value, String fieldName)