001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.freemarker;
016    
017    import com.liferay.portal.util.ClassLoaderUtil;
018    
019    import freemarker.ext.beans.BeansWrapper;
020    
021    import freemarker.template.TemplateMethodModelEx;
022    import freemarker.template.TemplateModelException;
023    
024    import java.util.List;
025    
026    /**
027     * @author Raymond Aug??
028     */
029    public class LiferayObjectConstructor implements TemplateMethodModelEx {
030    
031            @Override
032            public Object exec(@SuppressWarnings("rawtypes") List arguments)
033                    throws TemplateModelException {
034    
035                    if (arguments.isEmpty()) {
036                            throw new TemplateModelException(
037                                    "This method must have at least one argument as the name of " +
038                                            "the class to instantiate");
039                    }
040    
041                    Class<?> clazz = null;
042    
043                    try {
044                            String className = String.valueOf(arguments.get(0));
045    
046                            clazz = Class.forName(
047                                    className, true, ClassLoaderUtil.getContextClassLoader());
048                    }
049                    catch (Exception e) {
050                            throw new TemplateModelException(e.getMessage());
051                    }
052    
053                    BeansWrapper beansWrapper = BeansWrapper.getDefaultInstance();
054    
055                    Object object = beansWrapper.newInstance(
056                            clazz, arguments.subList(1, arguments.size()));
057    
058                    return beansWrapper.wrap(object);
059            }
060    
061    }