FieldBasedGetterSetter.java

package org.microspace.specific;

import java.lang.reflect.Field;

import org.microspace.annotation.IndexType;
import org.microspace.exception.IllegalOperationException;
import org.microspace.table.column.GetSetPair;

/**
 * SetterGetter based upon fields.
 * @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
 * @version 2016-06-26
 * @param <T> is the Table type.
 */
public class FieldBasedGetterSetter<T> extends GetSetPair<T> {
	
	Field field;
	IndexType indexType;
	String nullValue;
	int index;
	
	public FieldBasedGetterSetter (Field field) {
		this.field = field;
	}
	
	public void set(Object target, Object value) {
		try {
			field.set(target, value);
		} catch (IllegalAccessException e) {
			throw new IllegalOperationException ("Can not set field: " + getName(), e);
		}
	}

	public String getName() {
		return field.getName();
	}

	public Object get(Object target) {
		try {
			return field.get(target);
		} catch (IllegalAccessException e) {
			throw new IllegalOperationException ("Can not get field: " + getName(), e);
		}
	}

	public IndexType getIndexType() {
		return indexType;
	}
	public void setIndexType (IndexType indexType) {
		this.indexType = indexType;
	}
	public void setNullValue (String nullValue) {
		this.nullValue = nullValue;
	}

	private static byte nullByte;
	private static char nullChar;
	private static int nullInt;
	private static long nullLong;
	private static float nullFloat;
	private static double nullDouble;
	private static boolean nullBoolean;

	public boolean isNull (Object value) {
		if (value == null) return true;
		if (nullValue != null) {
			return nullValue.equals (value.toString());
		}
		if (!field.getType().isPrimitive()) return value == null;
		return isNullReturnType(value);
	}
	
	boolean isNullReturnType (Object obj) {
		if (obj == null) return true;
		Class<?> clazz = field.getType();
		if (clazz == byte.class) return obj.equals(nullByte);
		if (clazz == char.class) return obj.equals(nullChar);
		if (clazz == int.class) return obj.equals(nullInt);
		if (clazz == long.class) return obj.equals(nullLong);
		if (clazz == float.class) return obj.equals(nullFloat);
		if (clazz == double.class) return obj.equals(nullDouble);
		if (clazz == boolean.class) return obj.equals(nullBoolean);
		return false;
	}

	@Override
	public Class<?> getReturnType() {
		return field.getType();
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}
	
}