1 package edu.berkeley.sbp.util;
3 import java.lang.reflect.*;
4 import java.lang.annotation.*;
6 // FIXME: decent error reporting
7 /** Random reflection-related utilities */
8 public final class Reflection {
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;
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());
26 if (c == String.class) {
28 for(int i=0; i<a.length; i++)
29 if (a[i]==null || (!(a[i] instanceof Character) && !(a[i] instanceof String)))
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())+""
41 } else if (c.isArray()) {
42 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
45 } else if (c==int.class && o instanceof Number) { return o;
47 throw new Error("unable to cast " + o + " from " + o.getClass().getName() + " to " + c.getName());
52 public static Object[] newArray(Class c, int i) {
53 return (Object[])Array.newInstance(c, i);
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();
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() + " = ");
74 ret.append(show(f.get(o)));
75 } catch (Exception e) {
76 ret.append("**"+e+"**");
77 throw new RuntimeException(e);
80 return o.getClass().getName() + " {" + StringUtil.indent(ret.toString(), 4) + "\n}";
83 public static Object lub(Object argo) {
84 if (argo instanceof Object[]) return lub((Object[])argo);
87 public static Object[] lub(Object[] argo) {
88 if (argo==null) return 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());
95 if (c==null) c = Object.class;
96 Object[] ret = Reflection.newArray(c, argo.length);
97 System.arraycopy(argo, 0, ret, 0, argo.length);
101 public static Class lub(Class a, Class b) {
102 if (a==null) return b;
103 if (b==null) 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());
112 public static Class arrayClass(Class c) {
113 return Reflection.newArray(c, 0).getClass();
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) {
119 return Class.forName(s);
120 } catch (ClassNotFoundException _) {
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) {
129 Class[] argTypes = m instanceof Method ? ((Method)m).getParameterTypes() : ((Constructor)m).getParameterTypes();
131 Object[] args2 = new Object[args.length];
132 System.arraycopy(args, 0, args2, 0, args.length);
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;
139 args[i] = rebuild(args[i], goal);
141 throw new Error(e.getMessage() + "\n while trying to fuzzyInvoke("+m.getName()+")");
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]));
151 System.out.println(" arg => " + args[i] + (args[i]==null?"":(" (a " + args[i].getClass().getName() + ")")));
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);
162 private static String zoo(Object o) {
163 if (o==null) return "null";
164 if (o instanceof Object[]) {
166 for(int j=0; j<((Object[])o).length; j++)
167 ret += zoo(((Object[])o)[j]) + " ";
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;
178 public static boolean isStatic(Field f) {
179 if ((f.getModifiers() & Modifier.STATIC) != 0) return true;
183 public static Field getField(Class c, String s) {
185 for(Field f : c.getDeclaredFields())
186 if (f.getName().equals(s))
188 } catch (Exception e) { }
189 if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
190 return getField(c.getSuperclass(), s);
192 public static Field getField(Class c, int i) {
194 for(Field f : c.getDeclaredFields()) {
195 if (isStatic(f)) continue;
198 if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
199 return getField(c.getSuperclass(), i);
200 } catch (Exception e) { }
204 public static interface Show {
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);
213 public static Object impose(Class _class, Object[] fields) {
215 try { ret = _class.newInstance(); }
216 catch (Exception e) { rethrow(e, "while trying to instantiate a " + _class.getName()); }
217 Field[] f = _class.getFields();
219 for(int i=0; i<f.length; i++) {
220 Object tgt = Reflection.lub(fields[i]);
221 if (f[i].getType() == String.class) tgt = stringify(tgt);
223 tgt = coerce(tgt, f[i].getType());
226 } catch (Exception e) {
227 rethrow(e, "while setting \n " +
229 "\n to " + show(tgt));
235 public static Object rethrow(Exception e, String message) {
237 StackTraceElement[] st = e.getStackTrace();
238 RuntimeException re = new RuntimeException(e.getMessage() + "\n " + message);
239 re.setStackTrace(st);
243 public static Object impose(Method _method, Object[] fields) {
244 Object[] args = mkArgs(_method.getParameterTypes(), fields);
246 return _method.invoke(null, args);
247 } catch (Exception e) {
248 return rethrow(e, "while trying to invoke \n " +
250 "\n with arguments " + show(args));
253 public static Object impose(Constructor _ctor, Object[] fields) {
254 Object[] args = mkArgs(_ctor.getParameterTypes(), fields);
256 return _ctor.newInstance(args);
257 } catch (Exception e) {
258 return rethrow(e, "while trying to invoke \n " +
260 "\n with arguments " + show(args));
264 private static Object[] mkArgs(Class[] argTypes, Object[] fields) {
266 Object[] args = new Object[argTypes.length];
267 for(int i=0; i<args.length; i++) {
268 Object tgt = Reflection.lub(fields[i]);
269 if (argTypes[i] == String.class) tgt = Reflection.stringify(tgt);
271 tgt = Reflection.coerce(tgt, argTypes[i]);
277 public static String stringify(Object o) {
278 if (o==null) return "";
279 if (!(o instanceof Object[])) return o.toString();
280 Object[] arr = (Object[])o;
281 StringBuffer ret = new StringBuffer();
282 for(int i=0; i<arr.length; i++)
284 return ret.toString();
287 public static Object coerce(Object o, Class c) {
289 return coerce0(o, c);
290 } catch (Exception e) {
291 return (Object[])rethrow(e, "while trying to coerce " + show(o) + " to a " + c.getName());
294 public static Object coerce0(Object o, Class c) {
295 if (o==null) return null;
296 if (c.isInstance(o)) return o;
297 if (c == char.class) {
298 return o.toString().charAt(0);
300 if (c==int.class || c==Integer.class) {
301 String s = (String)coerce(o, String.class);
302 return new Integer(Integer.parseInt(s));
305 if (o.getClass().isArray() &&
306 o.getClass().getComponentType().isArray() &&
307 o.getClass().getComponentType().getComponentType() == String.class &&
309 c.getComponentType() == String.class) {
310 String[] ret = new String[((Object[])o).length];
311 for(int i=0; i<ret.length; i++) {
312 StringBuffer sb = new StringBuffer();
313 for(Object ob : (Object[])(((Object[])o)[i]))
315 ret[i] = sb.toString();
320 if (c.isArray() && (c.getComponentType().isInstance(o))) {
321 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
326 if (o.getClass().isArray() && c.isArray()) {
328 for(int i=0; i<((Object[])o).length; i++) {
329 Object ob = (((Object[])o)[i]);
335 return Array.newInstance(c.getComponentType(), ((Object[])o).length);