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