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