MethodBasedGetter.java

package org.microspace.specific;

import java.lang.reflect.Method;

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

/**
 * Method based getter.
 * 
 * @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
 * @version 2016-06-26
 * @param <T> is the Table type.
 */
public class MethodBasedGetter<T> implements Getter<T> {
	
	private final Method method;
	private final String name;
	private String nullValue;
	private IndexType indexType;
	
	public MethodBasedGetter (Method method, String name) {
		this.method = method;
		this.name = name;
	}
	
	public Method getMethod () {
		return method;
	}

	public String getName() {
		return name;
	}

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

	public Object get(T target) {
		if (target == null) return null;
		Object ret = null;
		try {
			ret = method.invoke (target);
		} catch (Exception e) {
			throw new IllegalOperationException ("Cant envoke " + method.getName(), e);
		}
		return ret;
	}
	
	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 field) {
		if (field == null) return true;
		if (nullValue != null) {
			return nullValue.equals (field.toString());
		}
		if (!method.getReturnType().isPrimitive()) return field == null;
		return isNullReturnType(field);
	}
	
	boolean isNullReturnType (Object obj) {
		if (obj == null) return true;
		Class<?> clazz = method.getReturnType();
		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 method.getReturnType();
	}
}