EFieldEval.java

/***************************************************************************
   Copyright 2012 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.simpletemplate.interpreter;


import java.lang.reflect.Field;
import java.util.Map;

import net.metanotion.util.Dictionary;
import net.metanotion.scripting.ObjectServer;
import net.metanotion.scripting.Struct;

final class EFieldEval implements Element {
	private static final Class[] envParam = new Class[] { Dictionary.class };

	private final Element object;
	private final String method;

	public EFieldEval(Element object, String method) {
		this.object = object;
		this.method = method;
	}

	@Override public Object eval(ObjectServer os, Object env) {
		final Object o = object.eval(os, env);
		if(o instanceof Map) {
			return ((Map) o).get(method);
		} else if(o instanceof Dictionary) {
			return ((Dictionary<String,Object>) o).get(method);
		} else if(o instanceof Struct) {
			return ((Struct) o).get(method);
		} else {
			final Class cls = o.getClass();
			try {
				return cls.getMethod(method, envParam).invoke(o, env);
			} catch (Exception e) {  }
			try {
				return cls.getMethod(method, null).invoke(o);
			} catch (Exception e) {  }
			try {
				return cls.getMethod("get" + method, envParam).invoke(o, env);
			} catch (NoSuchMethodException nsme) {
			} catch (IllegalAccessException iae) {
			} catch (java.lang.reflect.InvocationTargetException ite) { }
			try {
				return cls.getMethod("get" + method, null).invoke(o);
			} catch (NoSuchMethodException nsme) {
			} catch (IllegalAccessException iae) {
			} catch (java.lang.reflect.InvocationTargetException ite) { }
			try {
				final Field f = cls.getField(method);
				f.setAccessible(true);
				return f.get(o);
			} catch (Exception e) { throw new RuntimeException(e); }
		}
	}
}