Java Reflection Field Set setField(Field field, Object instance, Object value)

Here you can find the source of setField(Field field, Object instance, Object value)

Description

Sets the specified field to the specified value in the instance.

License

LGPL

Parameter

Parameter Description
field - The field to set
instance - The instance of the field to set
value - The value to set the field

Return

True if setting the field was successful.

Declaration

public static boolean setField(Field field, Object instance, Object value) 

Method Source Code

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

import java.lang.reflect.Field;

public class Main {
    /**/*from  w w  w.j  a  va2s  .com*/
     * Sets the specified field to the specified value in the instance.
     * 
     * @param field - The field to set
     * @param instance - The instance of the field to set
     * @param value - The value to set the field
     * @return True if setting the field was successful.
     */
    public static boolean setField(Field field, Object instance, Object value) {
        if (field == null) {
            System.err.println("Null field");
            return false;
        }
        try {
            field.set(instance, value);
        } catch (Exception e) {
            System.err.println(field.getType() + " not assignable from " + value.getClass());
            return false;
        }
        return true;
    }

    /**
     * Finds the first class that matches one of the names specified
     * 
     * @param classes - A list of all class names
     * @return The first class found, or null
     */
    public static Class<?> getClass(String... classes) {
        if (classes.length == 0) {
            System.err.println("No classes specified.");
            return null;
        }
        for (String name : classes) {
            try {
                return Class.forName(name);
            } catch (Throwable t) {
            }
        }

        return null;
    }
}

Related

  1. setField(Class clazz, T instance, String fieldName, Object value)
  2. setField(Field f, Object instance, Object value)
  3. setField(Field f, Object this_, Object value)
  4. setField(Field field, @Nullable Object instance, Object thing)
  5. setField(Field field, Object classWithField, Object value)
  6. setField(Field field, Object obj, String value)
  7. setField(Field field, Object objToSet, Object value)
  8. setField(Field field, Object target, Object value)
  9. setField(Field field, Object target, Object value)