01: /*
02: * Created on Nov 18, 2005
03: */
04: package uk.org.ponder.reflect;
05:
06: import java.lang.reflect.Constructor;
07: import java.lang.reflect.Method;
08: import java.util.Map;
09:
10: import uk.org.ponder.saxalizer.SAXAccessMethod;
11: import uk.org.ponder.util.UniversalRuntimeException;
12:
13: public class JDKReflectiveCache extends ReflectiveCache {
14:
15: /** Invokes the supplied no-arg Method object on the supplied target */
16: public static Object invokeMethod(Method method, Object target) {
17: return invokeMethod(method, target, SAXAccessMethod.emptyobj);
18: }
19:
20: /** Invokes the supplied Method object on the supplied target */
21: public static Object invokeMethod(Method method, Object target,
22: Object[] args) {
23: try {
24: return method.invoke(target, args);
25: } catch (Exception e) {
26: throw UniversalRuntimeException.accumulate(e);
27: }
28: }
29:
30: /** Invokes the supplied no-arg constructor to create a new object */
31: public static Object invokeConstructor(Constructor cons) {
32: Object togo = null;
33: try {
34: togo = cons.newInstance(SAXAccessMethod.emptyobj);
35: } catch (Exception e) {
36: throw UniversalRuntimeException.accumulate(e,
37: "Error constructing instance of "
38: + cons.getDeclaringClass());
39: }
40: return togo;
41: }
42:
43: public static Object invokeConstructor(Constructor cons,
44: Object[] args) {
45: Object togo = null;
46: try {
47: togo = cons.newInstance(args);
48: } catch (Exception e) {
49: throw UniversalRuntimeException.accumulate(e,
50: "Error constructing instance of "
51: + cons.getDeclaringClass());
52: }
53: return togo;
54: }
55:
56: public Object construct(Class clazz) {
57: Map classmap = getClassMap(clazz);
58: Constructor cons = (Constructor) classmap.get(CONSTRUCTOR_KEY);
59: if (cons == null) {
60: cons = getConstructor(clazz);
61: classmap.put(CONSTRUCTOR_KEY, cons);
62: }
63: return invokeConstructor(cons);
64: }
65:
66: public Object invokeMethod(Object target, String name) {
67: if (target instanceof MethodInvokingProxy) {
68: return ((MethodInvokingProxy) target).invokeMethod(name,
69: null);
70: }
71: Class clazz = target.getClass();
72: Map classmap = getClassMap(clazz);
73: Method method = (Method) classmap.get(name);
74: if (method == null) {
75: method = ReflectiveCache.getMethod(clazz, name);
76: classmap.put(name, method);
77: }
78: return invokeMethod(method, target);
79: }
80:
81: // This method currently bypassed - lookup of multi-arg methods is assumed
82: // slow and in ReflectiveCache
83: protected Object invokeMethod(Object target, String name,
84: Class[] argtypes, Object[] args) {
85: Class clazz = target.getClass();
86: Method toinvoke = ReflectiveCache.getMethod(clazz, name,
87: argtypes);
88: return invokeMethod(toinvoke, target, args);
89: }
90:
91: }
|