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 Object ret = _class.newInstance();
216 Field[] f = _class.getFields();
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);
222 tgt = coerce(tgt, f[i].getType());
226 } catch (Exception e) {
228 throw new RuntimeException(e);
232 public static Object impose(Method _method, Object[] fields) {
234 Class[] argTypes = _method.getParameterTypes();
235 Object[] args = new Object[argTypes.length];
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);
241 tgt = Reflection.coerce(tgt, argTypes[i]);
244 return _method.invoke(null, args);
245 } catch (Exception e) {
246 throw new RuntimeException(e);
250 public static Object impose(Constructor _ctor, Object[] fields) {
252 Class[] argTypes = _ctor.getParameterTypes();
253 Object[] args = new Object[argTypes.length];
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);
259 tgt = Reflection.coerce(tgt, argTypes[i]);
262 return _ctor.newInstance(args);
263 } catch (Exception e) {
264 throw new RuntimeException(e);
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++)
275 return ret.toString();
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);
284 if (c==int.class || c==Integer.class) {
285 String s = (String)coerce(o, String.class);
286 return new Integer(Integer.parseInt(s));
289 if (o.getClass().isArray() &&
290 o.getClass().getComponentType().isArray() &&
291 o.getClass().getComponentType().getComponentType() == String.class &&
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]))
299 ret[i] = sb.toString();
304 if (c.isArray() && (c.getComponentType().isInstance(o))) {
305 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
310 if (o.getClass().isArray() && c.isArray()) {
312 for(int i=0; i<((Object[])o).length; i++) {
313 Object ob = (((Object[])o)[i]);
319 return Array.newInstance(c.getComponentType(), ((Object[])o).length);