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

net.vidageek.mirror.get.GetterHandler Maven / Gradle / Ivy

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

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

import net.vidageek.mirror.MirrorException;

import static net.vidageek.mirror.Mirror.on;

/**
 * @author jonasabreu
 * 
 */
public class GetterHandler {

	private final Object target;
	private final Class clazz;

	public GetterHandler(final Object target) {
		if (target == null) {
			throw new IllegalArgumentException("target cannot be null");
		}
		clazz = target.getClass();
		this.target = target;
	}

	public GetterHandler(final Class clazz) {
		if (clazz == null) {
			throw new IllegalArgumentException("clazz cannot be null");
		}
		this.clazz = clazz;
		target = null;
	}

	public Object field(final String fieldName) {
		if (fieldName == null || fieldName.trim().length() == 0) {
			throw new IllegalArgumentException("fieldName cannot be null or empty.");
		}

		return field(getField(fieldName));
	}

	private Field getField(final String fieldName) {
		Field field = on(clazz).reflect().field(fieldName);
		if (field == null) {
			throw new MirrorException("could not find field " + fieldName + " for class " + clazz.getName());
		}
		return field;
	}

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

			if (target == null && !Modifier.isStatic(field.getModifiers())) {
				throw new IllegalStateException("attempt to get instance field " + field.getName() + " on class "
						+ clazz.getName());
			}

			field.setAccessible(true);
			return field.get(target);
		} catch (IllegalAccessException e) {
			throw new MirrorException("could not get falue for field " + field.getName() + " of class "
					+ clazz.getName());
		}

	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy