Java examples for Reflection:Field Set
set Field by name on Object
//package com.java2s; import java.lang.reflect.Field; public class Main { public static void setField(String name, Object target, Object value) { try {//w w w. j a va 2 s. co m Class<?> targetClass = target.getClass(); Field field = targetClass.getDeclaredField(name); boolean unlocked = false; if (!field.isAccessible()) { field.setAccessible(true); unlocked = true; } field.set(target, value); if (unlocked) { field.setAccessible(false); } } catch (Exception e) { throw new RuntimeException(e); } } }