01: package org.vraptor.component;
02:
03: import java.lang.reflect.Constructor;
04:
05: import org.vraptor.LogicRequest;
06: import org.vraptor.introspector.BeanProvider;
07:
08: /**
09: * A component constructor. It allows users to instantiate a component type
10: * using an specific bean provider.
11: *
12: * @author Guilherme Silveira
13: */
14: public class ComponentConstructor implements BeanConstructor {
15:
16: private final Constructor constructor;
17:
18: private final Class[] types;
19:
20: private final String[] keys;
21:
22: ComponentConstructor(Constructor constructor) {
23: this .constructor = constructor;
24: this .types = constructor.getParameterTypes();
25: this .keys = new String[types.length];
26: for (int i = 0; i < types.length; i++) {
27: keys[i] = types[i].getName();
28: }
29: }
30:
31: /* (non-Javadoc)
32: * @see org.vraptor.component.BeanConstructor#newInstance(org.vraptor.LogicRequest, org.vraptor.introspector.BeanProvider)
33: */
34: public Object newInstance(LogicRequest request,
35: BeanProvider provider)
36: throws ComponentInstantiationException {
37: Object[] values = new Object[keys.length];
38: for (int i = 0; i < keys.length; i++) {
39: values[i] = provider.findAttribute(request, keys[i]);
40: if (values[i] == null) {
41: throw new ComponentInstantiationException(
42: "Unable to fill value for key " + keys[i]);
43: }
44: }
45: try {
46: return constructor.newInstance(values);
47: } catch (Exception e) {
48: throw new ComponentInstantiationException(
49: "Unable to instantiate using " + constructor, e);
50: }
51: }
52:
53: @Override
54: public String toString() {
55: return constructor.getName() + keys.toString();
56: }
57:
58: }
|