All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.vidageek.mirror.set.FieldSetterByField Maven / Gradle / Ivy

/**
 * 
 */
package net.vidageek.mirror.set;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import net.vidageek.mirror.MirrorException;

/**
 * @author jonasabreu
 * 
 */
public class FieldSetterByField implements FieldSetter {

	private final Object target;
	private final Field field;
	private final Class clazz;

	public FieldSetterByField(final Object target, final Class clazz,
			final Field field) {
		if (clazz == null) {
			throw new IllegalArgumentException("clazz cannot be null");
		}
		if (field == null) {
			throw new IllegalArgumentException("field cannot be null");
		}
		if (!clazz.isAssignableFrom(field.getDeclaringClass())) {
			throw new IllegalArgumentException("field declaring class ("
					+ field.getDeclaringClass().getName()
					+ ") doesn't match clazz " + clazz.getName());
		}
		this.target = target;
		this.clazz = clazz;
		this.field = field;
	}

	@Override
	public void withValue(final Object value) {
		try {
			if (target == null && !Modifier.isStatic(field.getModifiers())) {
				throw new MirrorException("attempt to set instance field "
						+ field.getName() + " on class " + clazz.getName());
			}

			field.setAccessible(true);
			field.set(target, value);

		} catch (IllegalAccessException e) {
			throw new MirrorException("could not set value " + value
					+ " on field " + field.getName() + " of class "
					+ clazz.getName());
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy