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

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

Description

set Field

License

Apache License

Parameter

Parameter Description
target the target instance or Class<?> for static
name the field name
value the value

Declaration

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

Method Source Code


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

import java.lang.reflect.Field;

public class Main {
    /**//www  .j  a  va  2  s.c o m
     * @param target the target instance or Class<?> for static
     * @param name the field name
     * @param value the value
     */
    public static void setField(Object target, String name, Object value) {
        Class<?> theClass = null;
        if (target == null)
            throw new RuntimeException("no target object or class in setField(...)");
        if (target instanceof Class<?>) {
            theClass = (Class<?>) target;
        } else {
            theClass = target.getClass();
        }
        Field theField = null;
        while (theClass != null) {

            try {
                theField = theClass.getDeclaredField(name);
                break;
            } catch (NoSuchFieldException e) {
                theClass = theClass.getSuperclass();
            }

        }

        if (theField == null) {
            throw new RuntimeException(
                    "Didn't find the field " + name + " on " + target.toString() + " or any of its superclasses.");
        }
        try {
            theField.setAccessible(true);
            theField.set(target, value);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
}

Related

  1. setField(Object target, Field field, Object value)
  2. setField(Object target, String fieldName, Class fieldType, T value)
  3. setField(Object target, String fieldname, Object value)
  4. setField(Object target, String name, Object value)
  5. setField(Object target, String name, Object value)
  6. setField(Object target, String name, Object value)
  7. setField(Object targetObject, String fieldName, Object value, boolean failIfError)
  8. setField(String field, Object object, Object value)
  9. setField(String field, Object value)