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

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

Description

set Field

License

LGPL

Declaration

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

Method Source Code

//package com.java2s;
/**//www  . j  a va  2 s  .co m
 * Zephyrus
 * 
 * @author minnymin3
 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
 * 
 */

import java.lang.reflect.Field;

public class Main {
    public static void setField(Object obj, Object value, String fieldName) {
        try {
            getField(obj.getClass(), fieldName).set(obj, value);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * Retrieves a field
     * @param cl The class to retrieve the field from
     * @param fieldName The name of the field
     * @return
     */
    public static Field getField(Class<?> cl, String fieldName) {
        try {
            Field field = cl.getDeclaredField(fieldName);
            return field;
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

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