View Javadoc

1   /**
2    * This file Copyright (c) 2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.objectfactory;
35  
36  import java.lang.reflect.Constructor;
37  import java.lang.reflect.InvocationTargetException;
38  import java.lang.reflect.Modifier;
39  import javax.inject.Inject;
40  
41  
42  
43  /**
44   * Creates objects by dynamically resolving the parameters to use.
45   *
46   * @version $Id$
47   */
48  public class ObjectManufacturer {
49  
50      /**
51       * Creates an object of the given type using parameters provided by a set of parameter resolvers. Will first look
52       * for a constructor annotated with @Inject, it can be public, private, protected or package private. It will
53       * then look at public constructors and use the greediest. The greediest constructor is the one that has the most
54       * number of arguments that the parameter resolvers can fulfill. If there is more than one constructor that
55       * qualifies as greediest it is unspecified which one will be used.
56       */
57      public Object newInstance(Class<?> clazz, ParameterResolver... parameterResolvers) {
58  
59          Constructor<?>[] constructors = clazz.getDeclaredConstructors();
60  
61          Constructor<?> selectedConstructor = null;
62          for (Constructor<?> constructor : constructors) {
63              if (constructor.isAnnotationPresent(Inject.class)) {
64                  if (selectedConstructor != null) {
65                      throw new MgnlInstantiationException("Only one constructor can use @Inject [" + clazz + "]");
66                  }
67                  selectedConstructor = constructor;
68              }
69          }
70          if (selectedConstructor != null) {
71              selectedConstructor.setAccessible(true);
72              Object[] parameters = resolveParameters(selectedConstructor, parameterResolvers);
73              if (parameters == null) {
74                  throw new MgnlInstantiationException("Unable to resolve parameters for constructor " + selectedConstructor);
75              }
76              return newInstance(selectedConstructor, parameters);
77          }
78  
79          // Find greediest satisfiable constructor
80          int bestScore = -1;
81          Object[] bestParameters = null;
82          for (Constructor<?> constructor : constructors) {
83              if (!Modifier.isPublic(constructor.getModifiers())) {
84                  continue;
85              }
86              int score = constructor.getParameterTypes().length;
87              if (score < bestScore) {
88                  continue;
89              }
90              Object[] parameters = resolveParameters(constructor, parameterResolvers);
91              if (parameters == null) {
92                  continue;
93              }
94              selectedConstructor = constructor;
95              bestScore = score;
96              bestParameters = parameters;
97          }
98          if (selectedConstructor != null) {
99              return newInstance(selectedConstructor, bestParameters);
100         }
101         throw new MgnlInstantiationException("No suitable constructor found for class [" + clazz + "]");
102     }
103 
104     private Object newInstance(Constructor constructor, Object[] parameters) {
105         try {
106             return constructor.newInstance(parameters);
107         } catch (InstantiationException e) {
108             throw new MgnlInstantiationException(e);
109         } catch (IllegalAccessException e) {
110             throw new MgnlInstantiationException(e);
111         } catch (InvocationTargetException e) {
112             throw new MgnlInstantiationException(e);
113         }
114     }
115 
116     private Object[] resolveParameters(Constructor<?> constructor, ParameterResolver[] parameterResolvers) {
117         Object[] parameters = new Object[constructor.getParameterTypes().length];
118         for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) {
119             ParameterInfo constructorParameter = new ParameterInfo(constructor, parameterIndex);
120             Object parameter = resolveParameter(constructorParameter, parameterResolvers);
121             if (parameter == ParameterResolver.UNRESOLVED) {
122                 return null;
123             }
124             parameters[parameterIndex] = parameter;
125         }
126         return parameters;
127     }
128 
129     private Object resolveParameter(ParameterInfo constructorParameter, ParameterResolver[] parameterResolvers) {
130         for (ParameterResolver parameterResolver : parameterResolvers) {
131             Object parameter = parameterResolver.resolveParameter(constructorParameter);
132             if (parameter != ParameterResolver.UNRESOLVED) {
133                 return parameter;
134             }
135         }
136         return ParameterResolver.UNRESOLVED;
137     }
138 
139 }