1 28 29 package com.caucho.es.parser; 30 31 import com.caucho.es.ESBase; 32 import com.caucho.es.ESException; 33 34 import java.io.IOException ; 35 import java.lang.reflect.Constructor ; 36 import java.lang.reflect.Modifier ; 37 38 42 class JavaNewExpr extends CallExpr { 43 private Class javaClass; 44 45 private Constructor constructor; 46 47 JavaNewExpr(Block block, Class javaClass) 48 throws ESException 49 { 50 super(block, null, null, true); 51 52 this.javaClass = javaClass; 53 } 54 55 58 void addCallParam(Expr param) 59 { 60 param.setUsed(); 61 args.add(param); 62 } 63 64 int getType() 65 { 66 calculateType(); 67 68 return type; 69 } 70 71 Expr getTypeExpr() 72 { 73 calculateType(); 74 75 return typeExpr; 76 } 77 78 private void calculateType() 79 { 80 if (isCalculated) 81 return; 82 83 isCalculated = true; 84 85 if (javaClass == null) 86 return; 87 88 method = JavaMethod.bestMethod(javaClass, "create", true, args); 89 if (method == null || 90 ! method.getReturnType().equals(javaClass)) 91 method = null; 92 93 if (method != null) 94 term = new JavaClassExpr(block, javaClass); 95 96 Constructor []constructors = javaClass.getConstructors(); 97 Constructor bestConstructor = null; 98 int bestCost = Integer.MAX_VALUE; 99 100 for (int i = 0; i < constructors.length; i++) { 101 Constructor constructor = constructors[i]; 102 103 if (! Modifier.isPublic(constructor.getModifiers())) 104 continue; 105 106 Class []param = constructor.getParameterTypes(); 107 108 int cost = JavaMethod.methodCost(param, args); 109 110 if (cost < bestCost) { 111 bestCost = cost; 112 bestConstructor = constructor; 113 } 114 } 115 116 this.constructor = bestConstructor; 117 118 type = TYPE_JAVA; 119 typeExpr = new JavaTypeExpr(block, javaClass); 120 } 121 122 void printJavaImpl() 123 throws IOException 124 { 125 if (method != null) { 126 super.printJavaImpl(); 127 return; 128 } 129 130 if (constructor == null) 131 throw new IOException ("can't create `" + javaClass.getName() + "'"); 132 133 cl.print("new "); 134 135 cl.print(javaClass.getName()); 136 cl.print("("); 137 138 Class []params = null; 139 if (constructor != null) 140 params = constructor.getParameterTypes(); 141 142 for (int i = 0; i < params.length; i++) { 143 Expr expr; 144 145 if (i < args.size()) 146 expr = (Expr) args.get(i); 147 else 148 expr = block.newLiteral(ESBase.esUndefined); 149 150 if (i != 0) 151 cl.print(", "); 152 153 if (params != null && ! params[i].isPrimitive()) { 154 cl.print("("); 155 printJavaClass(params[i]); 156 cl.print(")"); 157 } 158 159 expr.printJava(); 160 } 161 cl.print(")"); 162 } 163 } 164 | Popular Tags |