1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
package org.apache.commons.inject.impl; |
18 | |
|
19 | |
import java.lang.reflect.Constructor; |
20 | |
import java.lang.reflect.Method; |
21 | |
|
22 | |
import org.apache.commons.inject.api.IBinding; |
23 | |
import org.apache.commons.inject.api.IInjector; |
24 | |
import org.apache.commons.inject.api.IPoint; |
25 | |
import org.apache.commons.inject.util.Exceptions; |
26 | |
|
27 | |
public class FactoryMethodProvider<T> extends AbstractBaseProvider<T> implements IInjectorAware { |
28 | |
private final Constructor<T> constructor; |
29 | |
private final Method method; |
30 | |
private final IBinding<Object>[] parameterBindings; |
31 | |
|
32 | |
public FactoryMethodProvider(Constructor<T> pConstructor, IPoint<T> pPoint, IBinding<Object>[] pBindings) { |
33 | 12 | super(pConstructor.getDeclaringClass(), pPoint); |
34 | 12 | constructor = pConstructor; |
35 | 12 | method = null; |
36 | 12 | parameterBindings = pBindings; |
37 | 12 | } |
38 | |
|
39 | |
@SuppressWarnings("unchecked") |
40 | |
public FactoryMethodProvider(Method pMethod, IBinding<Object>[] pBindings, IPoint<T> pPoint) { |
41 | 0 | super((Class<T>) pMethod.getReturnType(), pPoint); |
42 | 0 | constructor = null; |
43 | 0 | method = pMethod; |
44 | 0 | parameterBindings = pBindings; |
45 | |
|
46 | 0 | } |
47 | |
|
48 | |
@Override |
49 | |
public T get() { |
50 | |
try { |
51 | 50 | final Object[] parameters = new Object[parameterBindings.length]; |
52 | 122 | for (int i = 0; i < parameters.length; i++) { |
53 | 72 | parameters[i] = parameterBindings[i].getProvider().get(); |
54 | |
} |
55 | 50 | if (constructor == null) { |
56 | |
@SuppressWarnings("unchecked") |
57 | 0 | final T instance = (T) method.invoke(null, parameters); |
58 | 0 | return instance; |
59 | |
} else { |
60 | 50 | if (!constructor.isAccessible()) { |
61 | 12 | constructor.setAccessible(true); |
62 | |
} |
63 | 50 | return constructor.newInstance(parameters); |
64 | |
} |
65 | 0 | } catch (Throwable t) { |
66 | 0 | throw Exceptions.show(t); |
67 | |
} |
68 | |
} |
69 | |
|
70 | |
@Override |
71 | |
public void init(IInjector pInjector) { |
72 | 178 | for (IBinding<Object> binding : parameterBindings) { |
73 | 104 | if (binding instanceof IInjectorAware) { |
74 | 104 | ((IInjectorAware) binding).init(pInjector); |
75 | |
} |
76 | |
} |
77 | 74 | } |
78 | |
} |