1 16 package org.apache.commons.jexl.parser; 17 18 import java.lang.reflect.Array ; 19 import java.util.Collection ; 20 import java.util.Map ; 21 22 import org.apache.commons.jexl.JexlContext; 23 import org.apache.commons.jexl.util.Introspector; 24 import org.apache.commons.jexl.util.introspection.Info; 25 import org.apache.commons.jexl.util.introspection.VelMethod; 26 27 34 public class ASTSizeFunction extends SimpleNode { 35 40 public ASTSizeFunction(int id) { 41 super(id); 42 } 43 44 50 public ASTSizeFunction(Parser p, int id) { 51 super(p, id); 52 } 53 54 55 public Object jjtAccept(ParserVisitor visitor, Object data) { 56 return visitor.visit(this, data); 57 } 58 59 60 public Object value(JexlContext jc) throws Exception { 61 SimpleNode arg = (SimpleNode) jjtGetChild(0); 62 63 Object val = arg.value(jc); 64 65 if (val == null) { 66 throw new Exception ("size() : null arg"); 67 } 68 69 return new Integer (ASTSizeFunction.sizeOf(val)); 70 } 71 72 80 public static int sizeOf(Object val) throws Exception { 81 if (val instanceof Collection ) { 82 return ((Collection ) val).size(); 83 } else if (val.getClass().isArray()) { 84 return Array.getLength(val); 85 } else if (val instanceof Map ) { 86 return ((Map ) val).size(); 87 } else if (val instanceof String ) { 88 return ((String ) val).length(); 89 } else { 90 Object [] params = new Object [0]; 94 Info velInfo = new Info("", 1, 1); 95 VelMethod vm = Introspector.getUberspect().getMethod(val, "size", params, velInfo); 96 if (vm != null && vm.getReturnType() == Integer.TYPE) { 97 Integer result = (Integer ) vm.invoke(val, params); 98 return result.intValue(); 99 } 100 throw new Exception ("size() : unknown type : " + val.getClass()); 101 } 102 } 103 104 } 105 | Popular Tags |