Java Reflection Field Set setField(Class target, Class fieldType, int index, Object obj, Object value)

Here you can find the source of setField(Class target, Class fieldType, int index, Object obj, Object value)

Description

set Field

License

Open Source License

Declaration

public static void setField(Class<?> target, Class<?> fieldType, int index, Object obj, 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(Class<?> target, Class<?> fieldType, int index, Object obj, Object value) {
        try {//w  w w.  jav a 2s  .  c o  m
            getField(target, fieldType, index).set(obj, value);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Retrieve a field for the specific field type and index.
     * 
     * @param target - the target type.
     * @param fieldType - the field type.
     * @param index - the index.
     * @return The field
     */
    public static Field getField(Class<?> target, Class<?> fieldType, int index) {
        for (Field field : target.getDeclaredFields()) {
            if (fieldType.isAssignableFrom(field.getType()) && index-- <= 0) {
                field.setAccessible(true);
                return field;
            }
        }
        if (target.getSuperclass() != null)
            return getField(target.getSuperclass(), fieldType, index);
        throw new IllegalArgumentException("Cannot find field with type " + fieldType);
    }
}

Related

  1. setField(Class c, Object inst, String name, Object value)
  2. setField(Class cl, String name, Object obj, Object value)
  3. setField(Class clazz, Object instance, String field, Object value)
  4. setField(Class clazz, Object obj, String fieldName, Object value)
  5. setField(Class ownerClass, Object owner, String fieldName, Object newValue)
  6. setField(Class clazz, T instance, String fieldName, Object value)
  7. setField(Class clazz, T instance, String fieldName, Object value)
  8. setField(Field f, Object instance, Object value)
  9. setField(Field f, Object this_, Object value)