Here you can find the source of setField(Object object, String fieldName, int value)
Parameter | Description |
---|---|
object | the object that should be changed |
fieldName | the name of the field |
value | the value |
Parameter | Description |
---|---|
NoSuchFieldException | when the field does not exist or could not be written |
public static void setField(Object object, String fieldName, int value) throws NoSuchFieldException
//package com.java2s; import java.lang.reflect.Field; public class Main { /**/*from w w w . j av a2 s .c o m*/ * Sets a field value for the given object. * * @param object * the object that should be changed * @param fieldName * the name of the field * @param value * the value * @throws NoSuchFieldException * when the field does not exist or could not be written */ public static void setField(Object object, String fieldName, int value) throws NoSuchFieldException { setField(object, fieldName, Integer.valueOf(value)); } /** * Sets a field value for the given object. * * @param object * the object that should be changed * @param fieldName * the name of the field * @param value * the value * @throws NoSuchFieldException * when the field does not exist or could not be written */ public static void setField(Object object, String fieldName, Object value) throws NoSuchFieldException { try { Field field = null; Class instanceClass = object.getClass(); while (field == null) { try { field = instanceClass.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { instanceClass = instanceClass.getSuperclass(); if (instanceClass == null) { throw e; } } } field.setAccessible(true); field.set(object, value); } catch (SecurityException e) { e.printStackTrace(); throw new NoSuchFieldException("Unable to set field [" + fieldName + "]: " + e.toString()); } catch (IllegalArgumentException e) { e.printStackTrace(); throw new NoSuchFieldException("Unable to set field [" + fieldName + "]: " + e.toString()); } catch (IllegalAccessException e) { e.printStackTrace(); throw new NoSuchFieldException("Unable to set field [" + fieldName + "]: " + e.toString()); } } }