1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.onemind.commons.invoke;
22
23 import java.lang.reflect.Method;
24 import org.onemind.commons.java.lang.reflect.ReflectUtils;
25 /***
26 * An wrapper invocable that will use reflection
27 * to optionally use reflection for invocation
28 * if possible
29 * @author TiongHiang Lee (thlee@onemindsoft.org)
30 * @version $Id: ReflectionWrapperInvocable.java,v 1.4 2005/01/24 05:52:21 thlee Exp $ $Name: $
31 */
32 public class ReflectionWrapperInvocable extends AbstractInvocable
33 {
34
35 /***
36 * InvocableFunction which wrap a method
37 * @author TiongHiang Lee (thlee@onemindsoft.org)
38 * @version $Id: ReflectionWrapperInvocable.java,v 1.4 2005/01/24 05:52:21 thlee Exp $ $Name: $
39 */
40 private class ReflectMethodFunction extends AbstractInvocableFunction
41 {
42
43 /*** the method **/
44 private Method _method;
45
46 /***
47 * Constructor
48 * @param method the method
49 */
50 public ReflectMethodFunction(Method method)
51 {
52 super(method.getName(), method.getParameterTypes());
53 _method = method;
54 }
55
56 /***
57 * {@inheritDoc}
58 */
59 public Object invoke(Object target, Object[] args) throws Exception
60 {
61 return _method.invoke(target, args);
62 }
63 }
64
65 /*** the wrappee object **/
66 private Object _obj;
67
68 /*** whether use reflection **/
69 private boolean _reflect;
70
71 /***
72 * Constructor
73 * @param obj the wrappee
74 */
75 public ReflectionWrapperInvocable(Object obj)
76 {
77 this(obj, true);
78 }
79
80 /***
81 * Constructor
82 * @param obj the wrappee
83 * @param useReflect whether to use reflection
84 */
85 public ReflectionWrapperInvocable(Object obj, boolean useReflect)
86 {
87 _obj = obj;
88 _reflect = useReflect;
89 }
90
91 /***
92 * {@inheritDoc}
93 */
94 public boolean canInvoke(String functionName, Object[] args)
95 {
96 boolean result = super.canInvoke(functionName, args);
97 if (!result && _reflect)
98 {
99 try
100 {
101 ReflectUtils.getMethod(_obj.getClass(), functionName, args);
102 } catch (NoSuchMethodException e)
103 {
104
105 }
106 }
107 return result;
108 }
109
110 /***
111 * {@inheritDoc}
112 */
113 public InvocableFunction getFunction(String functionName, Object[] args)
114 {
115 InvocableFunction f = super.getFunction(functionName, args);
116 if (f == null && _reflect)
117 {
118 try
119 {
120 Method m = ReflectUtils.getMethod(_obj.getClass(), functionName, args);
121 f = new ReflectMethodFunction(m);
122 addFunction(f);
123 } catch (Exception e)
124 {
125
126 }
127 }
128 return f;
129 }
130
131 /***
132 * {@inheritDoc}
133 */
134 public Object invoke(String functionName, Object[] args) throws Exception
135 {
136 InvocableFunction f = getFunction(functionName, args);
137 if (f != null)
138 {
139 return f.invoke(_obj, args);
140 } else
141 {
142 throw new NoSuchMethodError("Method " + ReflectUtils.toMethodString(functionName, args) + " not found");
143 }
144 }
145 }