refactoring to eliminate Token.result()
[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
5 /** Random reflection-related utilities */
6 public final class Reflection {
7
8     private static Object rebuild(Object o, Class c) {
9         //System.out.println("rebuild " + o + " (a " + (o==null?null:o.getClass().getName()) + ") " + c);
10         if (o==null || c.isAssignableFrom(o.getClass())) return o;
11         if ((c == Character.class || c == Character.TYPE) && o instanceof String && ((String)o).length()==1) return new Character(((String)o).charAt(0));
12         if (o instanceof Character && c == String.class) return o+"";
13         if (o instanceof Object[]) {
14             Object[] a = (Object[])o;
15             if (c.isArray()) {
16                 Object[] ret = (Object[])Array.newInstance(c.getComponentType(), a.length);
17                 for(int i=0; i<ret.length; i++) {
18                     Object o2 = rebuild(a[i], c.getComponentType());
19                     //if (o2 != null) System.out.println("storing " + o2.getClass().getName() + " to " + c.getComponentType());
20                     ret[i] = o2;
21                 }
22                 return ret;
23             }
24             if (c == String.class) {
25                 boolean ok = true;
26                 for(int i=0; i<a.length; i++)
27                     if (a[i]==null || (!(a[i] instanceof Character) && !(a[i] instanceof String)))
28                         ok = false;
29                 if (ok) {
30                     StringBuffer s = new StringBuffer();
31                     for(int i=0; i<a.length; i++)
32                         s.append(a[i] instanceof Character
33                                  ? (((Character)a[i]).charValue())+""
34                                  : (String)a[i]
35                                  );
36                     return s.toString();
37                 }
38             }
39         } else if (c.isArray()) {
40             Object[] ret = (Object[])Array.newInstance(c.getComponentType(), 1);
41             ret[0] = o;
42             return ret;
43         } else {
44             throw new Error("unable to cast " + o + " from " + o.getClass().getName() + " to " + c.getName());
45         }
46         return o;
47     }
48
49     public static Object[] newArray(Class c, int i) {
50         return (Object[])Array.newInstance(c, i);
51     }
52
53     public static Object[] lub(Object[] argo) {
54         if (argo==null) return null;
55         Class c = null;
56         for(Object o : argo) if (o != null) c = Reflection.lub(c, o.getClass());
57         if (c==null) c = Object.class;
58         Object[] ret = Reflection.newArray(c, argo.length);
59         System.arraycopy(argo, 0, ret, 0, argo.length);
60         return ret;
61     }
62
63     public static Class lub(Class a, Class b) {
64         if (a==null) return b;
65         if (b==null) return a;
66         if (a==b) return a;
67         if (a.isAssignableFrom(b)) return a;
68         if (b.isAssignableFrom(a)) return b;
69         return lub(b, a.getSuperclass());
70     }
71
72     /** a version of <tt>Class.forName</tt> that returns <tt>null</tt> instead of throwing an exception */
73     public static Class forNameOrNull(String s) {
74         try {
75             return Class.forName(s); 
76         } catch (ClassNotFoundException _) {
77             return null;
78         }
79     }
80
81     /** invoke method/constructor m on object o with arguments args, and perform reasonable coercions as needed */
82     public static Object fuzzyInvoke(Object o, Member m, Object[] args) {
83         try {
84             Class[] argTypes = m instanceof Method ? ((Method)m).getParameterTypes() : ((Constructor)m).getParameterTypes();
85             boolean ok = true;
86             Object[] args2 = new Object[args.length];
87             System.arraycopy(args, 0, args2, 0, args.length);
88             args = args2;
89             for(int i=0; i<args.length; i++) {
90                 Class goal = argTypes[i];
91                 Class actual = args[i] == null ? null : args[i].getClass();
92                 if (args[i] == null || goal.isAssignableFrom(actual)) continue;
93                 try {
94                     args[i] = rebuild(args[i], goal);
95                 } catch (Error e) {
96                     throw new Error(e.getMessage() + "\n   while trying to fuzzyInvoke("+m.getName()+")");
97                 }
98             }
99             // for debugging
100             /*
101             System.out.println("\ninvoking " + o + "." + m);
102             for(int i=0; i<args.length; i++) {
103                 if (args[i] instanceof Object[]) {
104                     System.out.print("  arg => " + zoo(args[i]));
105                 } else {
106                     System.out.println("  arg => " + args[i] + (args[i]==null?"":(" (a " + args[i].getClass().getName() + ")")));
107                 }
108             }
109             */
110             // FIXME: deal with the case where it is an inner class ctor
111             return m instanceof Method ? ((Method)m).invoke(o, args) : ((Constructor)m).newInstance(args);
112         } catch (Exception e) {
113             throw new RuntimeException(e);
114         }
115     }
116
117     private static String zoo(Object o) {
118         if (o==null) return "null";
119         if (o instanceof Object[]) {
120             String ret = "[ ";
121             for(int j=0; j<((Object[])o).length; j++)
122                 ret += zoo(((Object[])o)[j]) + " ";
123             return ret+"]";
124         }
125         return o+"";
126     }
127
128 }