package ru.tehkode.utils;

import java.lang.reflect.Field;

/**
 * @author zml2008
 */
public class FieldReplacer<Instance, Type> {
	private final Class<Type> requiredType;
	private final Field field;

	public FieldReplacer(Class<? extends Instance> clazz, String fieldName, Class<Type> requiredType) {
		try {
			this.requiredType = requiredType;
			field = clazz.getDeclaredField(fieldName);

			field.setAccessible(true);
			if (!requiredType.isAssignableFrom(field.getType())) {
				throw new ExceptionInInitializerError("Field of wrong type");
			}
		} catch (NoSuchFieldException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public Type get(Instance instance) {
		try {
			return this.requiredType.cast(field.get(instance));
		} catch (IllegalAccessException e) {
			throw new Error(e);
		}
	}

	public void set(Instance instance, Type newValue) {
		try {
			field.set(instance, newValue);
		} catch (IllegalAccessException e) {
			throw new Error(e); // This shouldn't happen because we call setAccessible in the constructor
		}
	}
}

@@ -296,25 +296,16 @@
 Type) %7B%0A
-%09%09try %7B%0A%09
 %09%09this.r
@@ -338,17 +338,16 @@
 ;%0A%09%09
-%09
 field = 
 claz
@@ -346,45 +346,159 @@
 d = 
-clazz.getDeclaredField(fieldName
+getField(clazz, fieldName);%0A%09%09if (field == null) %7B%0A%09%09%09throw new ExceptionInInitializerError(%22No such field %22 + fieldName + %22 in class %22 + clazz
 );%0A
-%0A
 %09
+%09%7D%0A%0A
 %09%09fi
@@ -524,17 +524,16 @@
 rue);%0A%09%09
-%09
 if (!req
@@ -579,17 +579,16 @@
 e())) %7B%0A
-%09
 %09%09%09throw
@@ -648,95 +648,8 @@
 %22);%0A
-%09%09%09%7D%0A%09%09%7D catch (NoSuchFieldException e) %7B%0A%09%09%09throw new ExceptionInInitializerError(e);%0A
 %09%09%7D%0A
@@ -1060,11 +1060,285 @@
 r%0A%09%09%7D%0A%09%7D
+%0A%0A%09private static Field getField(Class%3C?%3E clazz, String fieldName) %7B%0A%09%09while (clazz != null && clazz != Object.class) %7B%0A%09%09%09try %7B%0A%09%09%09%09return clazz.getDeclaredField(fieldName);%0A%09%09%09%7D catch (NoSuchFieldException e) %7B%0A%09%09%09%09clazz = clazz.getSuperclass();%0A%09%09%09%7D%0A%09%09%7D%0A%09%09return null;%0A%09%7D
 %0A%7D%0A

Fix FieldReplacer to correctly replace fields in superclasses