1 package org.jicengine.element.impl; 2 3 import java.util.Arrays ; 4 5 import org.jicengine.element.ActionElement; 6 import org.jicengine.element.Element; 7 import org.jicengine.element.ElementCompiler; 8 import org.jicengine.element.ElementException; 9 import org.jicengine.element.Location; 10 import org.jicengine.element.VariableElement; 11 import org.jicengine.expression.ClassParser; 12 import org.jicengine.operation.Context; 13 import org.jicengine.operation.Operation; 14 import org.jicengine.operation.OperationException; 15 import org.jicengine.operation.ReflectionUtils; 16 17 public class ConstantOfElementCompiler extends ElementCompiler { 18 19 public ConstantOfElementCompiler(String name, Location location, String [] parameters) throws ElementException 20 { 21 super(name, location); 22 23 if( parameters.length == 1){ 24 try { 25 Class ownerClass = ClassParser.toClass(parameters[0]); 26 getElement().setConstructor(new ConstantOfConstructor(ownerClass)); 27 } catch (ClassNotFoundException e){ 28 throw new ElementException("Owner class not found",e, getName(), getLocation()); 29 } 30 } 31 else { 32 throw new ElementException("Expected 1 parameter, got " + parameters.length + " parameters: " + Arrays.asList(parameters), getName(),getLocation()); 33 } 34 } 35 36 protected ActionElement handleLooseVariableElement(VariableElement child) throws ElementException 37 { 38 throw new ElementException("Child elements not allowed", getName(), getLocation()); 39 } 40 41 public class ConstantOfConstructor implements Operation { 42 43 private Class ownerClass; 44 45 public ConstantOfConstructor(Class ownerClass) 46 { 47 this.ownerClass = ownerClass; 48 } 49 50 public Object execute(Context context) throws OperationException 51 { 52 try { 53 String fieldName = (String ) context.getObject(Element.VARIABLE_NAME_CDATA); 54 return getConstantValue(this.ownerClass, fieldName); 55 } catch (Exception e){ 56 throw new OperationException(e.getMessage(), e); 57 } 58 } 59 60 public boolean needsParameter(String name) 61 { 62 return name.equals(Element.VARIABLE_NAME_CDATA); 63 } 64 65 public boolean needsParameters() 66 { 67 return true; 68 } 69 } 70 71 public static Object getConstantValue(Class ownerClass, String fieldName) throws Exception 72 { 73 return ReflectionUtils.getFieldValue(null, ownerClass, fieldName); 74 } 75 } 76 | Popular Tags |