Here you can find the source of setFieldValueX(Object target, String field, Object value)
public final static void setFieldValueX(Object target, String field, Object value)
//package com.java2s; /*//from www.j a va 2 s. c o m * BJAF - Beetle J2EE Application Framework * ???J2EE??????????? * ??????2003-2015 ??? (www.beetlesoft.net) * * ?????????????????? *<http://www.apache.org/licenses/LICENSE-2.0> *???????????????????????? * * ??????????????????????????????? * ??? <yuhaodong@gmail.com/>. */ import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public final static void setFieldValueX(Object target, String field, Object value) { try { // Class<?> obj = target.getClass(); Field[] fields = getObjAllFields(target); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); if (field.equals(fields[i].getName())) { fields[i].set(target, value); break; } } } catch (Exception e) { throw new RuntimeException(e); } } private static Field[] getObjAllFields(Object object) { Class<?> clazz = object.getClass(); List<Field> fieldList = new ArrayList<>(); while (clazz != null) { fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } Field[] fields = new Field[fieldList.size()]; fieldList.toArray(fields); return fields; } }