checkpoint
[sbp.git] / src / edu / berkeley / sbp / util / Reflection.java
1 package edu.berkeley.sbp.util;
2 import java.io.*;
3 import java.lang.reflect.*;
4 import java.lang.annotation.*;
5
6 // FIXME: decent error reporting
7 /** Random reflection-related utilities */
8 public final class Reflection {
9     
10     public static Object rebuild(Object o, Class c) {
11         //System.out.println("rebuild " + o + " (a " + (o==null?null:o.getClass().getName()) + ") " + c);
12         if (o==null || c.isAssignableFrom(o.getClass())) return o;
13         if ((c == Character.class || c == Character.TYPE) && o instanceof String && ((String)o).length()==1) return new Character(((String)o).charAt(0));
14         if (o instanceof Character && c == String.class) return o+"";
15         if (o instanceof Object[]) {
16             Object[] a = (Object[])o;
17             if (c.isArray()) {
18                 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), a.length);
19                 for(int i=0; i<ret.length; i++) {
20                     Object o2 = rebuild(a[i], c.getComponentType());
21                     //if (o2 != null) System.out.println("storing " + o2.getClass().getName() + " to " + c.getComponentType());
22                     ret[i] = o2;
23                 }
24                 return ret;
25             }
26             if (c == String.class) {
27                 boolean ok = true;
28                 for(int i=0; i<a.length; i++)
29                     if (a[i]==null || (!(a[i] instanceof Character) && !(a[i] instanceof String)))
30                         ok = false;
31                 if (ok) {
32                     StringBuffer s = new StringBuffer();
33                     for(int i=0; i<a.length; i++)
34                         s.append(a[i] instanceof Character
35                                  ? (((Character)a[i]).charValue())+""
36                                  : (String)a[i]
37                                  );
38                     return s.toString();
39                 }
40             }
41         } else if (c.isArray()) {
42             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
43             ret[0] = o;
44             return ret;
45         } else if (c==int.class && o instanceof Number) { return o;
46         } else {
47             throw new Error("unable to cast " + o + " from " + o.getClass().getName() + " to " + c.getName());
48         }
49         return o;
50     }
51
52     public static Object[] newArray(Class c, int i) {
53         return (Object[])Array.newInstance(c, i);
54     }
55
56     public static String show(Object o) {
57         if (o==null) return "null";
58         if (o instanceof Show) return show((Show)o);
59         if (! (o instanceof Object[])) return o.toString() + " : " + o.getClass().getName();
60         Object[] arr = (Object[])o;
61         StringBuffer ret = new StringBuffer();
62         ret.append(o.getClass().getComponentType().getName());
63         ret.append("["+arr.length+"]:");
64         for(int i=0; i<arr.length; i++)
65             ret.append(StringUtil.indent("\n"+show(arr[i]), 4));
66         return ret.toString();
67     }
68
69     public static String show(Show o) {
70         StringBuffer ret = new StringBuffer();
71         for(Field f : o.getClass().getFields()) {
72             ret.append("\n" + f.getName() + " = ");
73             try {
74                 ret.append(show(f.get(o)));
75             } catch (Exception e) {
76                 ret.append("**"+e+"**");
77                 throw new RuntimeException(e);
78             }
79         }
80         return o.getClass().getName() + " {" + StringUtil.indent(ret.toString(), 4) + "\n}";
81     }
82
83     public static Object lub(Object argo) {
84         if (argo instanceof Object[]) return lub((Object[])argo);
85         return argo;
86     }
87     public static Object[] lub(Object[] argo) {
88         if (argo==null) return null;
89         Class c = null;
90         for(int i=0; i<argo.length; i++) {
91             if (argo[i]==null) continue;
92             argo[i] = lub(argo[i]);
93             c = Reflection.lub(c, argo[i].getClass());
94         }
95         if (c==null) c = Object.class;
96         Object[] ret = Reflection.newArray(c, argo.length);
97         System.arraycopy(argo, 0, ret, 0, argo.length);
98         return ret;
99     }
100
101     public static Class lub(Class a, Class b) {
102         if (a==null) return b;
103         if (b==null) return a;
104         if (a==b) return a;
105         if (a.isAssignableFrom(b)) return a;
106         if (b.isAssignableFrom(a)) return b;
107         if (a.isArray() && b.isArray())
108             return arrayClass(lub(a.getComponentType(), b.getComponentType()));
109         return lub(b, a.getSuperclass());
110     }
111
112     public static Class arrayClass(Class c) {
113         return Reflection.newArray(c, 0).getClass();
114     }
115
116     /** a version of <tt>Class.forName</tt> that returns <tt>null</tt> instead of throwing an exception */
117     public static Class forNameOrNull(String s) {
118         try {
119             return Class.forName(s); 
120         } catch (ClassNotFoundException _) {
121             return null;
122         }
123     }
124
125     public static Object fuzzyInvoke(Object o, Member m) { return fuzzyInvoke(o, m, new Object[0]); }
126     /** invoke method/constructor m on object o with arguments args, and perform reasonable coercions as needed */
127     public static Object fuzzyInvoke(Object o, Member m, Object[] args) {
128         try {
129             Class[] argTypes = m instanceof Method ? ((Method)m).getParameterTypes() : ((Constructor)m).getParameterTypes();
130             boolean ok = true;
131             Object[] args2 = new Object[args.length];
132             System.arraycopy(args, 0, args2, 0, args.length);
133             args = args2;
134             for(int i=0; i<args.length; i++) {
135                 Class goal = argTypes[i];
136                 Class actual = args[i] == null ? null : args[i].getClass();
137                 if (args[i] == null || goal.isAssignableFrom(actual)) continue;
138                 try {
139                     args[i] = rebuild(args[i], goal);
140                 } catch (Error e) {
141                     throw new Error(e.getMessage() + "\n   while trying to fuzzyInvoke("+m.getName()+")");
142                 }
143             }
144             // for debugging
145             /*
146             System.out.println("\ninvoking " + o + "." + m);
147             for(int i=0; i<args.length; i++) {
148                 if (args[i] instanceof Object[]) {
149                     System.out.print("  arg => " + zoo(args[i]));
150                 } else {
151                     System.out.println("  arg => " + args[i] + (args[i]==null?"":(" (a " + args[i].getClass().getName() + ")")));
152                 }
153             }
154             */
155             // FIXME: deal with the case where it is an inner class ctor
156             return m instanceof Method ? ((Method)m).invoke(o, args) : ((Constructor)m).newInstance(args);
157         } catch (Exception e) {
158             throw new RuntimeException(e);
159         }
160     }
161
162     private static String zoo(Object o) {
163         if (o==null) return "null";
164         if (o instanceof Object[]) {
165             String ret = "[ ";
166             for(int j=0; j<((Object[])o).length; j++)
167                 ret += zoo(((Object[])o)[j]) + " ";
168             return ret+"]";
169         }
170         return o+"";
171     }
172
173     public static boolean isConcrete(Class c) {
174         if ((c.getModifiers() & Modifier.ABSTRACT) != 0) return false;
175         if ((c.getModifiers() & Modifier.INTERFACE) != 0) return false;
176         return true;
177     }
178     public static boolean isStatic(Field f) {
179         if ((f.getModifiers() & Modifier.STATIC) != 0) return true;
180         return false;
181     }
182
183     public static Field getField(Class c, String s) {
184         try {
185             for(Field f : c.getDeclaredFields())
186                 if (f.getName().equals(s))
187                     return f;
188         } catch (Exception e) { }
189         if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
190         return getField(c.getSuperclass(), s);
191     }
192     public static Field getField(Class c, int i) {
193         try {
194             for(Field f : c.getDeclaredFields()) {
195                 if (isStatic(f)) continue;
196                 return f;
197             }
198             if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
199             return getField(c.getSuperclass(), i);
200         } catch (Exception e) { }
201         return null;
202     }
203
204     public static interface Show {
205     }
206
207     public static Object impose(Object o, Object[] fields) {
208         if (o instanceof Class) return impose((Class)o, fields);
209         if (o instanceof Method) return impose((Method)o, fields);
210         if (o instanceof Constructor) return impose((Constructor)o, fields);
211         return null;
212     }
213     public static Object impose(Class _class, Object[] fields) {
214         try {
215             Object ret = _class.newInstance();
216             Field[] f = _class.getFields();
217             int j = 0;
218             for(int i=0; i<f.length; i++) {
219                 Object tgt = Reflection.lub(fields[i]);
220                 if (f[i].getType() == String.class) tgt = stringify(tgt);
221                 // FUGLY
222                 tgt = coerce(tgt, f[i].getType());
223                 f[i].set(ret, tgt);
224             }
225             return ret;
226         } catch (Exception e) {
227             e.printStackTrace();
228             throw new RuntimeException(e);
229         }
230     }
231
232     public static Object impose(Method _method, Object[] fields) {
233         try {
234             Class[] argTypes = _method.getParameterTypes();
235             Object[] args = new Object[argTypes.length];
236             int j = 0;
237             for(int i=0; i<args.length; i++) {
238                 Object tgt = Reflection.lub(fields[i]);
239                 if (argTypes[i] == String.class) tgt = Reflection.stringify(tgt);
240                 // FUGLY
241                 tgt = Reflection.coerce(tgt, argTypes[i]);
242                 args[i] = tgt;
243             }
244             return _method.invoke(null, args);
245         } catch (Exception e) {
246             throw new RuntimeException(e);
247         }
248     }
249
250     public static Object impose(Constructor _ctor, Object[] fields) {
251         try {
252             Class[] argTypes = _ctor.getParameterTypes();
253             Object[] args = new Object[argTypes.length];
254             int j = 0;
255             for(int i=0; i<args.length; i++) {
256                 Object tgt = Reflection.lub(fields[i]);
257                 if (argTypes[i] == String.class) tgt = Reflection.stringify(tgt);
258                 // FUGLY
259                 tgt = Reflection.coerce(tgt, argTypes[i]);
260                 args[i] = tgt;
261             }
262             return _ctor.newInstance(args);
263         } catch (Exception e) {
264             throw new RuntimeException(e);
265         }
266     }
267
268     public static String stringify(Object o) {
269         if (o==null) return "";
270         if (!(o instanceof Object[])) return o.toString();
271         Object[] arr = (Object[])o;
272         StringBuffer ret = new StringBuffer();
273         for(int i=0; i<arr.length; i++)
274             ret.append(arr[i]);
275         return ret.toString();
276     }
277
278     public static Object coerce(Object o, Class c) {
279         if (o==null) return null;
280         if (c.isInstance(o)) return o;
281         if (c == char.class) {
282             return o.toString().charAt(0);
283         }
284         if (c==int.class || c==Integer.class) {
285             String s = (String)coerce(o, String.class);
286             return new Integer(Integer.parseInt(s));
287         }
288
289         if (o.getClass().isArray() &&
290             o.getClass().getComponentType().isArray() &&
291             o.getClass().getComponentType().getComponentType() == String.class &&
292             c.isArray() &&
293             c.getComponentType() == String.class) {
294             String[] ret = new String[((Object[])o).length];
295             for(int i=0; i<ret.length; i++) {
296                 StringBuffer sb = new StringBuffer();
297                 for(Object ob : (Object[])(((Object[])o)[i]))
298                     sb.append(ob);
299                 ret[i] = sb.toString();
300             }
301             return ret;
302         }
303
304         if (c.isArray() && (c.getComponentType().isInstance(o))) {
305             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
306             ret[0] = o;
307             return ret;
308         }
309
310         if (o.getClass().isArray() && c.isArray()) {
311             boolean ok = true;
312             for(int i=0; i<((Object[])o).length; i++) {
313                 Object ob = (((Object[])o)[i]);
314                 if (ob != null) {
315                     ok = false;
316                 }
317             }
318             if (ok) {
319                 return Array.newInstance(c.getComponentType(), ((Object[])o).length);
320             }
321         }
322         return o;
323     }
324
325 }