1 // Copyright 2006 all rights reserved; see LICENSE file for BSD-style license
3 package edu.berkeley.sbp.util;
5 import java.lang.reflect.*;
6 import java.lang.annotation.*;
8 // FIXME: decent error reporting
9 /** Random reflection-related utilities */
10 public final class Reflection {
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;
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());
28 if (c == String.class) {
30 for(int i=0; i<a.length; i++)
31 if (a[i]==null || (!(a[i] instanceof Character) && !(a[i] instanceof String)))
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())+""
43 } else if (c.isArray()) {
44 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
47 } else if (c==int.class && o instanceof Number) { return o;
49 throw new Error("unable to cast " + o + " from " + o.getClass().getName() + " to " + c.getName());
54 public static Object[] newArray(Class c, int i) {
55 return (Object[])Array.newInstance(c, i);
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();
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() + " = ");
76 ret.append(show(f.get(o)));
77 } catch (Exception e) {
78 ret.append("**"+e+"**");
79 throw new RuntimeException(e);
82 return o.getClass().getName() + " {" + StringUtil.indent(ret.toString(), 4) + "\n}";
85 public static Object lub(Object argo) {
86 if (argo instanceof Object[]) return lub((Object[])argo);
89 public static Object[] lub(Object[] argo) {
90 if (argo==null) return 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());
97 if (c==null) c = Object.class;
98 Object[] ret = Reflection.newArray(c, argo.length);
99 System.arraycopy(argo, 0, ret, 0, argo.length);
103 public static Class lub(Class a, Class b) {
104 if (a==null) return b;
105 if (b==null) 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());
114 public static Class arrayClass(Class c) {
115 return Reflection.newArray(c, 0).getClass();
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) {
121 return Class.forName(s);
122 } catch (ClassNotFoundException _) {
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) {
131 Class[] argTypes = m instanceof Method ? ((Method)m).getParameterTypes() : ((Constructor)m).getParameterTypes();
133 Object[] args2 = new Object[args.length];
134 System.arraycopy(args, 0, args2, 0, args.length);
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;
141 args[i] = rebuild(args[i], goal);
143 throw new Error(e.getMessage() + "\n while trying to fuzzyInvoke("+m.getName()+")");
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]));
153 System.out.println(" arg => " + args[i] + (args[i]==null?"":(" (a " + args[i].getClass().getName() + ")")));
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);
164 private static String zoo(Object o) {
165 if (o==null) return "null";
166 if (o instanceof Object[]) {
168 for(int j=0; j<((Object[])o).length; j++)
169 ret += zoo(((Object[])o)[j]) + " ";
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;
180 public static boolean isStatic(Field f) {
181 if ((f.getModifiers() & Modifier.STATIC) != 0) return true;
185 public static Field getField(Class c, String s) {
187 for(Field f : c.getDeclaredFields())
188 if (f.getName().equals(s))
190 } catch (Exception e) { }
191 if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
192 return getField(c.getSuperclass(), s);
194 public static Field getField(Class c, int i) {
196 for(Field f : c.getDeclaredFields()) {
197 if (isStatic(f)) continue;
200 if (c.getSuperclass()==null || c.getSuperclass()==c) return null;
201 return getField(c.getSuperclass(), i);
202 } catch (Exception e) { }
206 public static interface Show {
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);
215 public static Object impose(Class _class, Object[] fields) {
217 try { ret = _class.newInstance(); }
218 catch (Exception e) { rethrow(e, "while trying to instantiate a " + _class.getName()); }
219 Field[] f = _class.getFields();
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);
225 tgt = coerce(tgt, f[i].getType());
228 } catch (Exception e) {
229 rethrow(e, "while setting \n " +
231 "\n to " + show(tgt));
237 public static Object rethrow(Exception e, String message) {
239 StackTraceElement[] st = e.getStackTrace();
240 RuntimeException re = new RuntimeException(e.getMessage() + "\n " + message);
241 re.setStackTrace(st);
245 public static Object impose(Method _method, Object[] fields) {
246 Object[] args = mkArgs(_method.getParameterTypes(), fields);
248 return _method.invoke(null, args);
249 } catch (Exception e) {
250 return rethrow(e, "while trying to invoke \n " +
252 "\n with arguments " + show(args));
255 public static Object impose(Constructor _ctor, Object[] fields) {
256 Object[] args = mkArgs(_ctor.getParameterTypes(), fields);
258 return _ctor.newInstance(args);
259 } catch (Exception e) {
260 return rethrow(e, "while trying to invoke \n " +
262 "\n with arguments " + show(args));
266 private static Object[] mkArgs(Class[] argTypes, Object[] fields) {
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);
273 tgt = Reflection.coerce(tgt, argTypes[i]);
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++)
286 return ret.toString();
289 public static Object coerce(Object o, Class c) {
291 return coerce0(o, c);
292 } catch (Exception e) {
293 return (Object[])rethrow(e, "while trying to coerce " + show(o) + " to a " + c.getName());
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);
302 if (c==int.class || c==Integer.class) {
303 String s = (String)coerce(o, String.class);
304 return new Integer(Integer.parseInt(s));
307 if (o.getClass().isArray() &&
308 o.getClass().getComponentType().isArray() &&
309 o.getClass().getComponentType().getComponentType() == String.class &&
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]))
317 ret[i] = sb.toString();
322 if (c.isArray() && (c.getComponentType().isInstance(o))) {
323 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
328 if (o.getClass().isArray() && c.isArray()) {
330 for(int i=0; i<((Object[])o).length; i++) {
331 Object ob = (((Object[])o)[i]);
337 return Array.newInstance(c.getComponentType(), ((Object[])o).length);