Here you can find the source of setFieldVal(Object object, String name, Object val)
public static void setFieldVal(Object object, String name, Object val)
//package com.java2s; //License from project: Apache License import java.lang.reflect.Field; public class Main { public static void setFieldVal(Object object, String name, Object val) { Field field = getFieldByName(object.getClass(), name); field.setAccessible(true);//from w w w .j a v a 2s . c o m try { field.set(object, val); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static Field getFieldByName(Class<?> modelClass, String name) { Class<?> clazz = cloneClass(modelClass); Field field = null; for (int i = 0; i < 100; i++) { try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } catch (SecurityException e) { e.printStackTrace(); } if (field != null) break; } return field; } public static Class<?> cloneClass(Class<?> clazz) { Class<?> newClazz = null; try { newClazz = Class.forName(clazz.getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } return newClazz; } }