001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.ecm.platform.rendering.fm.extensions; 023 024import java.lang.reflect.Constructor; 025import java.util.List; 026 027import freemarker.template.TemplateMethodModelEx; 028import freemarker.template.TemplateModelException; 029 030/** 031 * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> 032 */ 033public class NewMethod implements TemplateMethodModelEx { 034 035 public Object exec(List arguments) throws TemplateModelException { 036 int size = arguments.size(); 037 if (size < 1) { 038 throw new TemplateModelException("Invalid number of arguments for new(class, ...) method"); 039 } 040 041 Class<?> klass; 042 try { 043 String className = (String) arguments.get(0); 044 klass = Class.forName(className); 045 if (size == 1) { 046 return klass.newInstance(); 047 } 048 } catch (ReflectiveOperationException e) { 049 throw new TemplateModelException("Failed to isntantiate the object", e); 050 } 051 arguments.remove(0); 052 Object[] ar = arguments.toArray(); 053 size--; 054 Constructor<?>[] ctors = klass.getConstructors(); 055 for (Constructor<?> ctor : ctors) { 056 Class<?>[] params = ctor.getParameterTypes(); // this is cloning params 057 if (params.length == size) { // try this one 058 try { 059 return ctor.newInstance(ar); 060 } catch (ReflectiveOperationException e) { 061 // continue 062 } 063 } 064 } 065 throw new TemplateModelException("No suitable constructor found"); 066 } 067 068}