Java: cambiar el valor de un atributo privado de un objeto

May 29, 2007 at 13:17

En Java a veces es necesario cambiar el valor de un atributo privado de un objeto. Por suerte, la reflexión nos permite hace esto de forma sencilla. El código, como vereis, no puede ser más simple:

public static void setField (Object o, String fieldName, Object newValue)
	throws IllegalArgumentException, IllegalAccessException {
	// Get all the object class fields
	final Field fields[] = o.getClass().getDeclaredFields();
	// Search the requested field
	for (int i = 0; i < fields.length; ++i)
		// If found, set its new value
		if (fieldName.equals(fields[i].getName())) {
			boolean accesible = fields[i].isAccessible();
			fields[i].setAccessible(true);
			fields[i].set(o, newValue);
			fields[i].setAccessible(accesible);
		}
}

Un sencillo código para hacer la prueba puede ser el siguiente, que juega con el atributo privado hash de la clase String:

public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
	String s = new String("abc");
	System.out.println("hashcode: " + s.hashCode());
	setField(s, "hash", 30);
	System.out.println("hashcode: " + s.hashCode());
}