1 52 53 package freemarker.core; 54 55 import java.util.List ; 56 57 import freemarker.ext.beans.BeansWrapper; 58 import freemarker.template.ObjectWrapper; 59 import freemarker.template.TemplateException; 60 import freemarker.template.TemplateMethodModelEx; 61 import freemarker.template.TemplateModel; 62 import freemarker.template.TemplateModelException; 63 import freemarker.template.TemplateScalarModel; 64 import freemarker.template.utility.ClassUtil; 65 66 71 72 class NewBI extends BuiltIn 73 { 74 75 static final Class TM_CLASS = TemplateModel.class; 76 static final Class BEAN_MODEL_CLASS = freemarker.ext.beans.BeanModel.class; 77 static Class JYTHON_MODEL_CLASS; 78 static { 79 try { 80 JYTHON_MODEL_CLASS = Class.forName("freemarker.ext.jython.JythonModel"); 81 } catch (Throwable e) { 82 JYTHON_MODEL_CLASS = null; 83 } 84 } 85 86 TemplateModel _getAsTemplateModel(Environment env) 87 throws TemplateException 88 { 89 TemplateModel tm = target.getAsTemplateModel(env); 90 String classname = null; 91 try { 92 classname = ((TemplateScalarModel) tm).getAsString(); 93 } 94 catch (ClassCastException cce) { 95 invalidTypeException(tm, target, env, "string"); 96 } 97 catch (NullPointerException npe) { 98 throw new InvalidReferenceException(getStartLocation() 99 + "\nCould not resolve expression: " + target, env); 100 } 101 return new ConstructorFunction(classname, env); 102 } 103 104 class ConstructorFunction implements TemplateMethodModelEx { 105 106 private final Class cl; 107 private final Environment env; 108 109 public ConstructorFunction(String classname, Environment env) throws TemplateException { 110 this.env = env; 111 try { 112 cl = ClassUtil.forName(classname); 113 if (!TM_CLASS.isAssignableFrom(cl)) { 114 throw new TemplateException("Class " + cl.getName() + " does not implement freemarker.template.TemplateModel", env); 115 } 116 if (BEAN_MODEL_CLASS.isAssignableFrom(cl)) { 117 throw new TemplateException("Bean Models cannot be instantiated using the ?new built-in", env); 118 } 119 if (JYTHON_MODEL_CLASS != null && JYTHON_MODEL_CLASS.isAssignableFrom(cl)) { 120 throw new TemplateException("Jython Models cannot be instantiated using the ?new built-in", env); 121 } 122 } 123 catch (ClassNotFoundException cnfe) { 124 throw new TemplateException(cnfe, env); 125 } 126 } 127 128 public Object exec(List arguments) throws TemplateModelException { 129 ObjectWrapper ow = env.getObjectWrapper(); 130 BeansWrapper bw = 131 ow instanceof BeansWrapper 132 ? (BeansWrapper)ow 133 : BeansWrapper.getDefaultInstance(); 134 return (TemplateModel) bw.newInstance(cl, arguments); 135 } 136 } 137 } 138 | Popular Tags |