Here you can find the source of setFieldContent(final Object obj, final String name, final Object value)
Parameter | Description |
---|---|
obj | Object. |
name | Variable name. |
value | Value to set. |
Parameter | Description |
---|---|
NoSuchFieldException | Variable of given name was not found. |
public static void setFieldContent(final Object obj, final String name, final Object value) throws NoSuchFieldException
//package com.java2s; /* This file is part of the project "Hilbert II" - http://www.qedeq.org * * Copyright 2000-2013, Michael Meyling <mime@qedeq.org>. * * "Hilbert II" is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. *//*from www. j a va 2s . c om*/ import java.lang.reflect.Field; public class Main { /** * This method sets the contents of an object variable. The class hierarchy is recursively * searched to find such a field (even if it is private). * * @param obj Object. * @param name Variable name. * @param value Value to set. * @throws NoSuchFieldException Variable of given name was not found. */ public static void setFieldContent(final Object obj, final String name, final Object value) throws NoSuchFieldException { final Field field = getField(obj, name); try { field.set(obj, value); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /** * Get field of given name in given object. The class hierarchy is recursively searched * to find such a field (even if it is private). * * @param obj Object to work on. * @param name Search this field. * @return Found field. * @throws NoSuchFieldException Field with name <code>name</code> was not found. */ public static Field getField(final Object obj, final String name) throws NoSuchFieldException { Field field = null; try { Class cl = obj.getClass(); while (!Object.class.equals(cl)) { try { field = cl.getDeclaredField(name); break; } catch (NoSuchFieldException ex) { cl = cl.getSuperclass(); } } if (field == null) { throw (new NoSuchFieldException(name + " within " + obj.getClass())); } field.setAccessible(true); } catch (SecurityException e) { throw new RuntimeException(e); } return field; } }