1
2
3
4
5
6
7
8 package de.keepondreaming.xml;
9
10 import java.lang.reflect.InvocationHandler;
11 import java.lang.reflect.Method;
12 import java.lang.reflect.Proxy;
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19
20 import de.keepondreaming.xml.util.Util;
21
22 /***
23 * Creates a runtime proxy for an interface. Adds the interface
24 * {@link de.keepondreaming.xml.ClassProxyAccess} to ease attribute access
25 *
26 * $Author: wintermond $
27 * $Date: 2005/07/09 09:54:22 $
28 * $Log: ClassProxy.java,v $
29 * Revision 1.4 2005/07/09 09:54:22 wintermond
30 * Javadoc and implemented ProxyClassCreator
31 *
32 * Revision 1.3 2005/07/09 08:25:49 wintermond
33 * new cvs substitution tag
34 *
35 */
36 public class ClassProxy implements InvocationHandler, ClassProxyAccess
37 {
38
39 /***
40 * Attributes set by the application get stored here
41 */
42 Map<String, Object> entriesM = new HashMap<String, Object>();
43
44 /***
45 * Default constructor
46 */
47 public ClassProxy()
48 {
49 super();
50 }
51
52
53
54
55 public Object invoke(Object arg0, Method method, Object[] parameters)
56 throws Throwable
57 {
58 Object result = null;
59 String name = method.getName();
60
61
62
63
64 if(ClassProxyAccess.class.isAssignableFrom(method.getDeclaringClass()))
65 {
66 if(name.startsWith("set"))
67 {
68 setAttribute((String) parameters[0], parameters[1]);
69 }
70 else
71 {
72 result = getAttribute((String) parameters[0]);
73 }
74 }
75 else if(ProxyClassCreator.class.isAssignableFrom(method.getDeclaringClass()))
76 {
77 result = getWrappedClass(arg0);
78 }
79
80
81
82 else if(name.startsWith("get"))
83 {
84
85
86
87 String key = new String(name.substring(3));
88 result = entriesM.get(key);
89 Class returnType = method.getReturnType();
90
91
92
93
94 if(result == null)
95 {
96 if(returnType.isPrimitive())
97 {
98 result = Util.createPrimitiveDefaultValue(returnType);
99 }
100 else if(returnType.isInterface())
101 {
102 if(List.class.isAssignableFrom(returnType))
103 {
104 result = new ArrayList();
105 }
106 else if(Set.class.isAssignableFrom(returnType))
107 {
108 result = new HashSet();
109 }
110 else if(Map.class.isAssignableFrom(returnType))
111 {
112 result = new HashMap();
113 }
114 else
115 {
116 result = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{returnType, ClassProxyAccess.class}, new ClassProxy());
117 }
118 entriesM.put(key, result);
119
120 }
121 }
122 }
123
124
125 return result;
126
127 }
128
129
130
131
132
133
134 public Object getAttribute(String key)
135 {
136 return entriesM.get(key);
137
138 }
139
140
141
142
143 public void setAttribute(String key, Object value)
144 {
145 entriesM.put(key, value);
146 }
147
148
149
150
151 public Class getWrappedClass(Object object)
152 {
153
154 return object.getClass().getInterfaces()[0];
155 }
156 }