Here you can find the source of setField(Class> target, Class> fieldType, int index, Object obj, Object value)
public static void setField(Class<?> target, Class<?> fieldType, int index, Object obj, Object value)
//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); } }