1 /******************************************************************************
2 * Copyright (C) PicoContainer Organization. All rights reserved. *
3 * ------------------------------------------------------------------------- *
4 * The software in this package is published under the terms of the BSD *
5 * style license a copy of which has been included with this distribution in *
6 * the license.html file. *
7 * *
8 * Idea by Rachel Davies, Original code by Aslak Hellesoy and Paul Hammant *
9 *****************************************************************************/
10
11 package org.picocontainer.defaults;
12
13 import org.picocontainer.PicoIntrospectionException;
14 import org.picocontainer.internals.ComponentFactory;
15 import org.picocontainer.internals.ComponentSpecification;
16
17 import java.lang.reflect.Constructor;
18 import java.lang.reflect.InvocationTargetException;
19 import java.io.Serializable;
20
21 /***
22 * CompoentFactory that supports IoC type 3, which is constructor based.
23 *
24 * @author Aslak Hellesoy
25 * @version $Revision: 1.8 $
26 */
27 public class DefaultComponentFactory implements ComponentFactory, Serializable {
28 public Object createComponent(ComponentSpecification componentSpec, Object[] instanceDependencies) throws PicoInvocationTargetInitializationException, NoPicoSuitableConstructorException {
29 try {
30 Constructor constructor = getConstructor(componentSpec.getComponentImplementation());
31 return constructor.newInstance(instanceDependencies);
32 } catch (InvocationTargetException e) {
33 throw new PicoInvocationTargetInitializationException(e.getCause());
34 } catch (InstantiationException e) {
35 throw new RuntimeException(e);
36 } catch (IllegalAccessException e) {
37 throw new RuntimeException(e);
38 }
39 }
40
41 public Class[] getDependencies(Class componentImplementation) throws PicoIntrospectionException {
42 Constructor constructor = getConstructor(componentImplementation);
43 return constructor.getParameterTypes();
44 }
45
46 /***
47 * This is now IoC 2.5 compatible. Multi ctors next.
48 * @param componentImplementation
49 * @return
50 * @throws NoPicoSuitableConstructorException
51 */
52 private Constructor getConstructor(Class componentImplementation) throws NoPicoSuitableConstructorException {
53 Constructor[] constructors = componentImplementation.getConstructors();
54 Constructor picoConstructor = null;
55 for (int i = 0; i < constructors.length; i++) {
56 Constructor constructor = constructors[i];
57 if (constructor.getParameterTypes().length != 0 || constructors.length == 1) {
58 if (picoConstructor != null) {
59 throw new NoPicoSuitableConstructorException(componentImplementation);
60 }
61 picoConstructor = constructor;
62 }
63 }
64 if (picoConstructor == null) {
65 throw new NoPicoSuitableConstructorException(componentImplementation);
66 }
67 // Get the pico enabled constructor
68 return picoConstructor;
69 }
70 }
This page was automatically generated by Maven