Here you can find the source of setField(Object target, String name, Object value)
Parameter | Description |
---|---|
target | the target instance or Class<?> for static |
name | the field name |
value | the value |
public static void setField(Object target, String name, Object value)
//package com.java2s; //License from project: Apache License import java.lang.reflect.Field; public class Main { /**//www .j a va 2 s.c o m * @param target the target instance or Class<?> for static * @param name the field name * @param value the value */ public static void setField(Object target, String name, Object value) { Class<?> theClass = null; if (target == null) throw new RuntimeException("no target object or class in setField(...)"); if (target instanceof Class<?>) { theClass = (Class<?>) target; } else { theClass = target.getClass(); } Field theField = null; while (theClass != null) { try { theField = theClass.getDeclaredField(name); break; } catch (NoSuchFieldException e) { theClass = theClass.getSuperclass(); } } if (theField == null) { throw new RuntimeException( "Didn't find the field " + name + " on " + target.toString() + " or any of its superclasses."); } try { theField.setAccessible(true); theField.set(target, value); } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }