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

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

Description

set Field

License

Open Source License

Declaration

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

Method Source Code


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

import java.lang.reflect.Field;

public class Main {
    public static void setField(Object o, String fieldName, Object value) {
        try {//from www .  j  a  v a  2 s .c  om
            Field field = null;
            try {
                field = o.getClass().getField(fieldName);
            } catch (NoSuchFieldException e) {
                try {
                    o.getClass().getDeclaredField(fieldName).setAccessible(true);
                    field = o.getClass().getField(fieldName);
                } catch (NoSuchFieldException ex) {
                    ex.printStackTrace();
                }
            }
            field.set(o, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object getField(Object o, String fieldName) {
        try {
            return o.getClass().getField(fieldName).get(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

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