Here you can find the source of setField(Object target, Field field, Object value)
Parameter | Description |
---|---|
target | Object whose field is being set |
field | Object field to set |
value | the new value for the given field |
public static void setField(Object target, Field field, Object value)
//package com.java2s; /*/*ww w . ja v a2s . c om*/ * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ import java.lang.reflect.Field; public class Main { /** * Set target Object field to a certain value * * @param target Object whose field is being set * @param field Object field to set * @param value the new value for the given field */ public static void setField(Object target, Field field, Object value) { try { field.set(target, value); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Field " + field + " could not be set", e); } } /** * Set target Object field to a certain value * * @param target Object whose field is being set * @param fieldName Object field naem to set * @param value the new value for the given field */ public static void setField(Object target, String fieldName, Object value) { try { Field field = getField(target.getClass(), fieldName); field.set(target, value); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Field " + fieldName + " could not be set", e); } } /** * Get a field from a given class * * @param clazz clazz * @param name field name * * @return field object */ public static Field getField(Class clazz, String name) { try { Field field = clazz.getDeclaredField(name); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { Class superClass = clazz.getSuperclass(); if (!clazz.equals(superClass)) { return getField(superClass, name); } throw new IllegalArgumentException("Class " + clazz + " does not contain a " + name + " field", e); } } }